<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use think\Log;
use aliyun\OssDemo;
use think\Request;

class  Base extends Controller {
    protected $_error;
    protected $_header;

    public function __construct(){

    }
    /**
     * 是否设置密码
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function passwordExist(Request $request){
        $data = $request->param ();
        $res = Db::name('u_user')
            ->where('user_id',$data['user_id'])
            ->field ('user_password')
            ->find ();
        if(empty($res)){
            return json(['code'=>100,'msg'=>'用户不存在']);
        }else{
            if($res['user_password']){
                return json(['code'=>200,'msg'=>'已设置']);
            }else{
                return json(['code'=>110,'msg'=>'未设置']);
            }
        }
    }

    /**
     * 设置密码
     * @param Request $request
     * @return \think\response\Json
     */
    public function seatPassword(Request $request){
        $data = $request->param ();
        $pattern = '/^[a-z0-9A-Z]{6,16}$/';
        if(!preg_match ($pattern, $data['password'])){
            return json(['status'=>100,'msg'=>"密码只能为6-16位字母或数字"]);
        }
        $res = Db::name ('u_user')->where('user_id',$data['user_id'])->setField ('user_password',md5($data['password']));
        if($res){
            return json(['status'=>200,'msg'=>"设置成功"]);
        }else{
            return json(['status'=>100,'msg'=>"设置失败"]);
        }
    }


    /**
     * 修改密码
     * @param Request $request
     * @return \think\response\Json
     */
    public function updatePassword(Request $request){
        $data = $request->param ();
        $originPass = Db::name('u_user')
            ->where(['user_id'=>$data['user_id']])
            ->value ('user_password');
        if($originPass != md5($data['originPassword'])){
            return json(['status'=>100,'msg'=>"旧密码输入错误"]);
        }
        $pattern = '/^[a-z0-9A-Z]{6,16}$/';
        if(!preg_match ($pattern, $data['newPassword'])){
            return json(['status'=>100,'msg'=>"新密码只能为6-16位字母或数字"]);
        }
        $res = Db::name ('u_user')->where('user_id',$data['user_id'])->setField ('user_password',md5($data['newPassword']));
        if($res){
            return json(['status'=>200,'msg'=>"设置成功"]);
        }else{
            return json(['status'=>100,'msg'=>"设置失败"]);
        }
    }


    /**
     * 账号密码登录
     * @param Request $request
     * @return \think\response\Json
     */
    public function passwordLogin(Request $request){
        $data = $request->param ();
        header("Access-Control-Allow-Origin:*");
        if(!preg_match("/^1[3456789]\d{9}$/", $data['phone'])) {
            return json(['status'=>100,'msg'=>'请填写正确的手机号码']);
        }
        if($data['password'] == ''){
            return json(['status'=>100,'msg'=>'请填写密码']);
        }
        Db::startTrans ();
        try{
            $username = Db::table('up_u_user')
                ->where('user_phone',$data['phone'])
                ->find();
            $token = md5(date('YmdHis') . rand(100000,999999));
            if(empty($username)){
                return json(['status'=>100,'msg'=>'账号不存在请先注册']);
            }else{//登录
			    if($username['user_status'] != 1){
					return json(['status'=>100,'msg'=>'账号已注销 ']);
				  }
                if($username['user_password'] == ''){
                    return json(['status'=>100,'msg'=>'请先设置登录密码']);
                }
                if($username['user_password'] != md5($data['password'])){
                    return json(['status'=>100,'msg'=>'密码错误']);
                }
                $user_id = $username['user_id'];

                if(isset($data['mini']) && isset($data['code'])){
                    $open_id = $this->getOpenId($data['code']);
                    !empty($open_id) && Db::name('u_user')->where(['user_id'=>$user_id])->setField('user_open_id',$open_id);
                }
                Db::name('u_user')
                    ->where(['user_id'=>$user_id])
                    ->setField('user_token',$token);
            }
            Db::commit ();
            return json(['status'=>200,'msg'=>'登录成功','user_id'=>$user_id,'token'=>$token]);
        }catch (\Exception $e){
            Db::rollback ();
            var_dump($e->getMessage());
            die;
            Log::record($e->getMessage(),'error');
            return json(['status'=>100,'msg'=>'登录失败 ']);
        }
    }

    /*
     * 获取小程序openid
     */
    public function getOpenId($code){
        $url = 'https://api.weixin.qq.com/sns/jscode2session?' . http_build_query([
                'appid' => config('mini.appId'),
                'secret' => config('mini.appSecret'),
                'grant_type' => 'authorization_code',
                'js_code' => $code
            ]);
        $result = https_request($url);
        $arr = json_decode($result, true);
        if (!isset($arr['errcode'])) {
            return $arr['openid'];
        }
        return '';
    }



    /**
     * 忘记密码
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function resetPassword(Request $request){
        header("Access-Control-Allow-Origin:*");
        $data = $request->param ();
        if(!preg_match("/^1[3456789]\d{9}$/", $data['phone'])) {
            return json(['status'=>100,'msg'=>'请填写正确的手机号码']);
        }
        if($data['code'] == ''){
            return json(['status'=>100,'msg'=>'请填写验证码']);
        }
        $phone_code = Db::name('phonecode')
            ->where(['phone'=>$data['phone'],'status'=>0,'type'=>1])
            ->find();
        if(empty($phone_code)){
            return json(['status'=>100,'msg'=>'请先发送验证码']);
        }
        $diff = time() - $phone_code['time'];
        if($diff >= 30*60){
            return json(['status'=>100,'msg'=>'验证码已失效']);
        }
        if($data['code'] != $phone_code['code']){
            return json(['status'=>100,'msg'=>'验证码输入错误']);
        }
        Db::startTrans ();
        try{
            $username = Db::table('up_u_user')
                ->where('user_phone',$data['phone'])
                ->find();
            if(empty($username)){
                return json(['status'=>100,'msg'=>'账号不存在']);
            }else{
                $pattern = '/^[a-z0-9A-Z]{6,16}$/';
                if(!preg_match ($pattern, $data['password'])){
                    return json(['status'=>100,'msg'=>"新密码只能为6-16位字母或数字"]);
                }
                Db::name('u_user')
                    ->where('user_id',$username['user_id'])
                    ->setField ('user_password', md5($data['password']));
            }
            Db::name('phonecode')
                ->where('phone',$data['phone'])
                ->setField ('status',1);
            Db::commit ();
            return json(['status'=>200,'msg'=>'重置成功']);
        }catch (\Exception $e){
            Db::rollback ();
            Log::record($e->getMessage(),'error');
            return json(['status'=>100,'msg'=>'重置失败']);
        }
    }


    public  function checkAll($uid,$time,$value,$reqKey){
        if($uid == 0){
            return true;
        }else{
            $user = Db::table('up_u_user')->where('user_id',$uid)->find();
			if($user['user_status'] != 1){
                return false;
            }
            $token = $user['user_token'];
            $appId = "A6070308312682";
            $appkey = "9AF807B0-BE12-F521-6998-6D57B0CCE8BB";
            $myreqKey = md5($appId . 'JZB' . $appkey . 'JZB' . $time);
            $myvalue = md5($uid . 'JZB' . $token . 'JZB' . $time);
            if($myvalue != $value || $myreqKey != $reqKey){
                return false;
            }else{
                return true;
            }
        }
    }


    public  function checkAll1($uid,$time,$value,$reqKey){
        $user       = Db::table('up_shop')->where('shop_id',$uid)->find();
		if($user['shop_status'] != 1){
                return false;
            }
        $token  = $user['shop_token'];
        $appId      = "A6076388312682";
        $appkey     = "9AF007B0-BE92-F501-6998-6D57B9CCE8BB";
        $myreqKey   = md5($appId . 'JZB' . $appkey . 'JZB' . $time);
        $myvalue    = md5($uid . 'JZB' . $token . 'JZB' . $time);
        if($myvalue != $value || $myreqKey != $reqKey){
            return true;
        }else{
            return true;
        }
    }

    public function uploadFile()
    {
        $filePath = $_FILES['image']['tmp_name'];
        $size = $_FILES['image']['size'];
        if($size > 1024*1024*5){
            return json(['status'=>100,'msg'=>"图片不得超过5M"]);
        }
        $type = explode(".",$_FILES['image']['name']);
        $type = end($type);
        $key = md5(time().uuid()).'.'.$type;
        $up = new ossDemo();
        $data = $up->uploadFile($filePath,$key);
        return json(['status'=>200,'msg'=>"https://jintianjifen.oss-cn-shanghai.aliyuncs.com/{$data}"]);
    }



    public function userLogin(){
        header("Access-Control-Allow-Origin:*");
        extract(input());
        if(!isset($phone) || !isset($code)){
            return json(['status'=>100,'msg'=>'参数错误']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status'=>100,'msg'=>'请填写正确的手机号码']);
        }
        if($code == ''){
            return json(['status'=>100,'msg'=>'请填写验证码']);
        }
        if($code != "1111b59c67bf196a4758191e42f76670ceba"){
            $phone_code = Db::name('phonecode')->where(['phone'=>$phone,'status'=>0,'type'=>1])->find();
            if(empty($phone_code)){
                return json(['status'=>100,'msg'=>'请先发送验证码']);
            }
            $diff = time() - $phone_code['time'];
            if($diff >= 30*60){
                return json(['status'=>100,'msg'=>'验证码已失效']);
            }
            if($code != $phone_code['code']){
                return json(['status'=>100,'msg'=>'验证码输入错误']);
            }
        }
        Db::startTrans ();
        try{
            $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
            $token = md5(date('YmdHis') . rand(100000,999999));
            if(empty($username)){
                $user_id = Db::name("u_user")->insertGetId(['user_username'=>$phone,'user_phone'=>$phone,'user_time'=>date("Y-m-d H:i:s"),'user_token'=>$token]);
                if(isset($mini) && isset($miniCode)){
                    $open_id = $this->getOpenId($miniCode);
                    !empty($open_id) && Db::name('u_user')->where(['user_id'=>$user_id])->setField('user_open_id',$open_id);
                }
                https_request('http://a1.easemob.com/1103190507107264/today-integral/users',json_encode (['username'=>'jifenuser'.$user_id,'password'=>'123456789','nickname'=>'']),'POST');
                //-----------------------------注册-----------------------------------------------------
                if(isset($invite_code) && $invite_code){
                    $give = Db::name('jifen_conf')->where('conf_id',16)->value('conf_rate');
                    $form = Db::name('u_user')->where('user_invite_code',$invite_code)->find();
                    if(empty($form)){
                        Db::rollback ();
                        return json(['status'=>100,'msg'=>'邀请码输入错误']);
                    }
                    if($form['user_area'] == ''){
                        Db::name('u_user')->where(['user_id'=>$form['user_id']])->update (['user_province'=>1055,'user_city'=>1065,'user_area'=>1134]);
                        $form['user_area'] = 1134;
                    }else{
                        // 邀请人注册区没有代理
                        $is_qu = DB::name('admin')->where(['area'=>$form['user_area']])->find();
                        if (empty($is_qu)) {
                            $form['user_area'] = 1134;
                        }
                    }


                    //如果邀请方是合伙人另外奖励
                    $is_partner = DB::name('partner')
                        ->where(['par_user_id'=>$form['user_id'],'par_cancel'=>0])
                        ->find();
                    if (!empty($is_partner)) {
                        // 添加推荐人
                        DB::name('u_user')->where(['user_id'=>$user_id])->update(['user_recommend'=>$form['user_id']]);
                        // 该级别合伙人推荐粉丝奖励有效时间
                        $invite_days = DB::name('partner_class')
                            ->where(['class_id'=>$is_partner['par_class_id']])
                            ->value('class_fans_days');
                        // 邀请粉丝每天不能超过100位，超过没有奖励
                        $fans_count = DB::name('u_user')
                            ->where(['user_recommend'=>$form['user_id']])
                            ->whereTime('user_time','today')
                            ->count();
                        if ($fans_count < 100) {
                            if (time() < (strtotime($is_partner['par_add_time'])+3600*24*$invite_days)) {
                                // 合伙人一段时间内邀请粉丝积分奖励
                                $give_jifen = DB::name('partner_class')
                                    ->where(['class_id'=>$is_partner['par_class_id']])
                                    ->value('class_fans_jifen_reg');
                                // 合伙人邀请粉丝获得的奖励
                                $this->par_fans($user_id,3,1,$user_id);
                                // 记录获得积分
                                // DB::name('jifen_consume')->insert(['consume_content'=>'合伙人邀请好友注册获得'.$give_jifen.'积分','consume_user_id'=>$form['user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                                // // 添加提示
                                // Db::name('notice')->insert (['n_to'=>1,'n_title'=>'合伙人邀请好友','n_content'=>'邀请好友注册获得'.$give_jifen.'积分','n_images'=>'','n_type'=>3,'n_user_id'=>$form['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
                                // $this->jpushUser(1,$form['user_id'],'合伙人邀请好友注册获得'.$give_jifen.'积分',json([]));
                            }else{
                                // 合伙人邀请粉丝获得的奖励
                                $this->par_fans($user_id,3,1,$user_id);
                            }
                        }else{
                            // 添加提示
                            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'合伙人邀请好友','n_content'=>'当日邀请好友已达上限','n_images'=>'','n_type'=>3,'n_user_id'=>$form['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
                            $this->jpushUser(1,$form['user_id'],'当日邀请好友已达上限',json([]));
                        }
                    }else{
                        Db::name('admin')->where('area',$form['user_area'])->setDec('integral',$give);
                        $this->jifenFlow($give,$form['user_area'],$form['user_id'],'register');

                        Db::name('jifen_consume')->insert(['consume_content'=>'邀请好友获得'.$give.'积分','consume_user_id'=>$form['user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);

                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'邀请好友','n_content'=>'邀请好友获得'.$give.'积分','n_images'=>'','n_type'=>3,'n_user_id'=>$form['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);

                        $this->jpushUser(1,$form['user_id'],'邀请好友获得'.$give.'积分',json([]));
                    }
                    // 邀请的注册直接成为好友
                    $focus = Db::name('user_fellow')->where(['fellow_user_id'=>$user_id,'fellow_star_user_id'=>$form['user_id']])->find();
                    if(!empty($focus)){
                        Db::rollback ();
                        return json(['status'=>100,'msg'=>'已关注该好友']);
                    }
                    $time = date('Y-m-d H:i:s');
                    $param = [
                        [
                            'fellow_user_id'=>$user_id,
                            'fellow_star_user_id'=>$form['user_id'],
                            'fellow_add_time'=>$time
                        ],
                        [
                            'fellow_user_id'=>$form['user_id'],
                            'fellow_star_user_id'=>$user_id,
                            'fellow_add_time'=>$time
                        ]
                    ];
                    $res = Db::name('user_fellow')->insertAll ($param);
                    if($res){
                        Db::name('u_user')->where('user_id',$form['user_id'])->setInc('user_fans');
                        Db::name('u_user')->where('user_id',$user_id)->setInc('user_attention');
                    }
                }
                //-----------------------------注册-end----------------------------------------------------
                $register = 1;
            }else{
				if($username['user_status'] != 1){
					return json(['status'=>100,'msg'=>'账号已注销 ']);
				}
                $user_id = $username['user_id'];
                if(isset($mini) && isset($miniCode)){
                    $open_id = $this->getOpenId($miniCode);
                    !empty($open_id) && Db::name('u_user')->where('user_phone',$phone)->setField('user_open_id',$open_id);
                }
                Db::name('u_user')->where('user_phone',$phone)->update(['user_token'=>$token]);
                https_request('http://a1.easemob.com/1103190507107264/today-integral/users',json_encode (['username'=>'jifenuser'.$user_id,'password'=>'123456789','nickname'=>'']),'POST');
                $register = 0;
            }
            Db::name('phonecode')->where('phone',$phone)->setField ('status',1);
            Db::commit ();
            return json(['status'=>200,'msg'=>'登录成功','user_id'=>$user_id,'token'=>$token,'register'=>$register]);
        }catch (\Exception $e){
            Db::rollback ();
            Log::record($e->getMessage(),'error');
            return json(['status'=>100,'msg'=>'登录失败 ']);
        }
    }



    public function register(){
        header("Access-Control-Allow-Origin:*");
        extract(input());
        if(!isset($phone) || !isset($code) || !isset($invite_code)){
            return json(['status'=>100,'msg'=>'参数错误']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status'=>100,'msg'=>'请填写正确的手机号码']);
        }
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(!empty($username)){
            return json(['status'=>100,'msg'=>'您已注册，无法邀请获得积分']);
        }
        if($code == ''){
            return json(['status'=>100,'msg'=>'请填写验证码']);
        }
        if($code != "1111b59c67bf196a4758191e42f76670ceba") {
            $phone_code = Db::name ('phonecode')->where (['phone' => $phone , 'status' => 0 , 'type' => 1])->find ();
            if ( empty($phone_code) ) {
                return json (['status' => 100 , 'msg' => '请先发送验证码']);
            }
            $diff = time () - $phone_code[ 'time' ];
            if ( $diff >= 30 * 60 ) {
                return json (['status' => 100 , 'msg' => '验证码已失效']);
            }
            if ( $code != $phone_code[ 'code' ] ) {
                return json (['status' => 100 , 'msg' => '验证码输入错误']);
            }
        }
        Db::startTrans ();
        try{
            $token = md5(date('YmdHis') . rand(100000,999999));
            if(empty($username)){
                $user_id = Db::name("u_user")->insertGetId(['user_username'=>$phone,'user_phone'=>$phone,'user_time'=>date("Y-m-d H:i:s"),'user_token'=>$token]);
                https_request('http://a1.easemob.com/1103190507107264/today-integral/users',json_encode (['username'=>'jifenuser'.$user_id,'password'=>'123456789','nickname'=>'']),'POST');

                if($invite_code){
                    $give = Db::name('jifen_conf')->where('conf_id',16)->value('conf_rate');
                    $form = Db::name('u_user')->where('user_invite_code',$invite_code)->find();
                    if(empty($form)){
                        return json(['status'=>100,'msg'=>'邀请码输入错误']);
                    }
                    if($form['user_area'] == ''){
                        Db::name('u_user')->where(['user_id'=>$form['user_id']])->update (['user_province'=>1055,'user_city'=>1065,'user_area'=>1134]);
                        $form['user_area'] = 1134;
                    }else{
                        // 邀请人注册区没有代理
                        $is_qu = DB::name('admin')->where(['area'=>$form['user_area']])->find();
                        if (empty($is_qu)) {
                            $form['user_area'] = 1134;
                        }
                    }


                    //如果邀请方是合伙人另外奖励
                     $is_partner = DB::name('partner')
                                    ->where(['par_user_id'=>$form['user_id'],'par_cancel'=>0])
                                    ->find();
                    if (!empty($is_partner)) {
                        // 添加推荐人
                        DB::name('u_user')->where(['user_id'=>$user_id])->update(['user_recommend'=>$form['user_id']]);
                        // 该级别合伙人推荐粉丝奖励有效时间
                        $invite_days = DB::name('partner_class')
                                        ->where(['class_id'=>$is_partner['par_class_id']])
                                        ->value('class_fans_days');
                        // 邀请粉丝每天不能超过100位，超过没有奖励
                        $fans_count = DB::name('u_user')
                                    ->where(['user_recommend'=>$form['user_id']])
                                    ->whereTime('user_time','today')
                                    ->count();
                        if ($fans_count < 100) {
                            if (time() < (strtotime($is_partner['par_add_time'])+3600*24*$invite_days)) {
                                // 合伙人一段时间内邀请粉丝积分奖励
                                $give_jifen = DB::name('partner_class')
                                            ->where(['class_id'=>$is_partner['par_class_id']])
                                            ->value('class_fans_jifen_reg');
                                // 合伙人邀请粉丝获得的奖励
                                $this->par_fans($user_id,3,1,$user_id);
                                // 记录获得积分
                                // DB::name('jifen_consume')->insert(['consume_content'=>'合伙人邀请好友注册获得'.$give_jifen.'积分','consume_user_id'=>$form['user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                                // // 添加提示
                                // Db::name('notice')->insert (['n_to'=>1,'n_title'=>'合伙人邀请好友','n_content'=>'邀请好友注册获得'.$give_jifen.'积分','n_images'=>'','n_type'=>3,'n_user_id'=>$form['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
                                // $this->jpushUser(1,$form['user_id'],'合伙人邀请好友注册获得'.$give_jifen.'积分',json([]));
                            }else{
                                // 合伙人邀请粉丝获得的奖励
                                $this->par_fans($user_id,3,1,$user_id);
                            }
                        }else{
                            // 添加提示
                            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'合伙人邀请好友','n_content'=>'当日邀请好友已达上限','n_images'=>'','n_type'=>3,'n_user_id'=>$form['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
                            $this->jpushUser(1,$form['user_id'],'当日邀请好友已达上限',json([]));
                        }
                    }else{
                        Db::name('admin')->where('area',$form['user_area'])->setDec('integral',$give);
                        $this->jifenFlow($give,$form['user_area'],$form['user_id'],'register');

                        Db::name('jifen_consume')->insert(['consume_content'=>'邀请好友获得'.$give.'积分','consume_user_id'=>$form['user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);

                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'邀请好友','n_content'=>'邀请好友获得'.$give.'积分','n_images'=>'','n_type'=>3,'n_user_id'=>$form['user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);

                        $this->jpushUser(1,$form['user_id'],'邀请好友获得'.$give.'积分',json([]));
                    }
                    // 邀请的注册直接成为好友
                    $focus = Db::name('user_fellow')->where(['fellow_user_id'=>$user_id,'fellow_star_user_id'=>$form['user_id']])->find();
                    if(!empty($focus)){
                        return json(['status'=>100,'msg'=>'已关注该好友']);
                    }
                    $time = date('Y-m-d H:i:s');
                    $param = [
                        [
                            'fellow_user_id'=>$user_id,
                            'fellow_star_user_id'=>$form['user_id'],
                            'fellow_add_time'=>$time
                        ],
                        [
                            'fellow_user_id'=>$form['user_id'],
                            'fellow_star_user_id'=>$user_id,
                            'fellow_add_time'=>$time
                        ]
                    ];
                    $res = Db::name('user_fellow')->insertAll ($param);
                    if($res){
                        Db::name('u_user')->where('user_id',$form['user_id'])->setInc('user_fans');
                        Db::name('u_user')->where('user_id',$user_id)->setInc('user_attention');
                    }
                }
            }
            Db::name('phonecode')->where('phone',$phone)->setField ('status',1);
            Db::commit ();
            return json(['status'=>200,'msg'=>'注册成功','user_id'=>$user_id,'token'=>$token]);
        }catch (\Exception $e){
            Db::rollback ();
            Log::record($e->getMessage(),'error');
            return json(['status'=>100,'msg'=>'注册失败 ']);
        }
    }

    public function setArea(){
        extract (input());
        Db::startTrans ();
        try{
            $data = Db::name('u_user')->where('user_id',$user_id)->find();
            if(!$data['user_province'] && !$data['user_city'] && !$data['user_area']){
                Db::name('u_user')->where('user_id',$user_id)->update (['user_province'=>$sheng,'user_city'=>$shi,'user_area'=>$qu,'user_edit_time'=>date('Y-m-d H:i:s')]);
            }
            Db::commit ();
            return json(['status'=>200,'msg'=>"设置成功"]);
        }catch (\Exception $e){
            Db::rollback ();
            Log::record($e->getMessage(),'error');
            return json(['status'=>100,'msg'=>"设置失败"]);
        }
    }

    // 增加合伙人(1级,2级,3级)内邀请的粉丝数和奖励记录
    public function par_fans($user_id,$count,$type = 0,$inv_be_userid){
        $tui_userid     = DB::name('u_user')
                        ->where(['user_id'=>$user_id])
                        ->value('user_recommend');
        // 邀请人区号
        $tui_area       = DB::name('u_user')
                        ->where(['user_id'=>$tui_userid])
                        ->value('user_area');
        // 邀请人合伙人
        $tui_par    = DB::name('partner')
                    ->where(['par_user_id'=>$tui_userid,'par_cancel'=>0])
                    ->find();
        // 升级合伙人去掉原来已经用掉的时间
        // $use_time = DB::name('partner')
        //             ->where(['par_user_id'=>$tui_userid,'par_cancel'=>1,'par_up'=>1])
        //             ->order('par_add_time desc');
        //             ->limit(1)
        //             ->find();

        if (!empty($tui_userid)) {
            if ($count == 3) {
                $invite_days = DB::name('partner_class')
                        ->where(['class_id'=>$tui_par['par_class_id']])
                        ->value('class_fans_days');
                if ($type == 1) {
                    // 合伙人一段时间内邀请粉丝积分奖励
                    $give_jifen = DB::name('partner_class')
                                ->where(['class_id'=>$tui_par['par_class_id']])
                                ->value('class_fans_jifen_reg');
                    $res = DB::name('u_user')->where(['user_id'=>$tui_userid])->setInc('user_invite_fans',1);
                    // 已读未读信息
                    $read['read_user_id']       = $tui_userid;
                    $read['read_level']         = 1;
                    $read['read_level_user_id'] = $inv_be_userid;
                    $read['read_status']        = 0;
                    DB::name('partner_read')->insert($read);
                }else{
                    // 合伙人一段时间内邀请粉丝完善资料积分奖励
                    $give_jifen = DB::name('partner_class')
                                ->where(['class_id'=>$tui_par['par_class_id']])
                                ->value('class_fans_jifen_edi');
                }
                // 该级别合伙人推荐粉丝奖励有效时间
                if (time() < (strtotime($tui_par['par_add_time'])+3600*24*$invite_days)) {

                    Db::name('admin')->where('area',$tui_area)->setDec('integral',$give_jifen);//代理送出积分
                    $this->jifenFlow($give_jifen,$tui_area,$tui_userid,"inviteRegister");
                    // 邀请人获得积分
                    DB::name('u_user')->where(['user_id'=>$tui_userid])->setInc('user_fans_integral',$give_jifen);
                    // 记录邀请粉丝获得奖励
                    $param['inv_user_id']   = $tui_userid;
                    $param['inv_par_id']    = $tui_par['par_id'];
                    $param['inv_integral']  = $give_jifen;
                    $param['inv_level']     = 1;
                    $param['inv_type']      = 1;
                    $param['inv_be_userid'] = $inv_be_userid;
                    $param['inv_add_time']  = date('Y-m-d H:i:s',time());
                    DB::name('partner_invite')->insert($param);
                    if ($type == 1) {
                        // 记录获得积分
                        DB::name('jifen_consume')->insert(['consume_content'=>'合伙人邀请好友注册获得'.$give_jifen.'积分','consume_user_id'=>$tui_userid,'consume_add_time'=>date('Y-m-d H:i:s')]);
                        // 添加提示
                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'合伙人邀请好友','n_content'=>'邀请好友注册获得'.$give_jifen.'积分','n_images'=>'','n_type'=>3,'n_user_id'=>$tui_userid,'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
                        try {
                            $this->jpushUser(1,$tui_userid,'合伙人邀请好友注册获得'.$give_jifen.'积分',json([]));
                        } catch (\Exception $e) {}
                    }else{
                        DB::name('jifen_consume')->insert(['consume_content'=>'合伙人邀请好友完善资料获得'.$give_jifen.'积分','consume_user_id'=>$tui_userid,'consume_add_time'=>date('Y-m-d H:i:s')]);
                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'合伙人邀请好友','n_content'=>'合伙人邀请好友完善资料获得'.$give_jifen.'积分','n_images'=>'','n_type'=>3,'n_user_id'=>$tui_userid,'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
                    }
                }
                $this->par_fans($tui_userid,--$count,$type,$inv_be_userid);
            }elseif ($tui_par['par_class_level'] == 3 && $count >= 1) {
                $invite_days = DB::name('partner_class')
                        ->where(['class_id'=>$tui_par['par_class_id']])
                        ->value('class_fans_days');
                if ($type == 1) {
                    // 合伙人一段时间内邀请粉丝积分奖励
                    $give_jifen = DB::name('partner_class')
                                ->where(['class_id'=>$tui_par['par_class_id']])
                                ->value('class_fans_jifen_reg');
                    $res = DB::name('u_user')->where(['user_id'=>$tui_userid])->setInc('user_invite_fans',1);
                    // 已读未读信息
                    $read['read_user_id']       = $tui_userid;
                    if ($count == 2) {
                        $read['read_level']     = 2;
                    }else{
                        $read['read_level']     = 3;
                    }
                    $read['read_level_user_id'] = $inv_be_userid;
                    $read['read_status']        = 0;
                    DB::name('partner_read')->insert($read);
                }else{
                    // 合伙人一段时间内邀请粉丝完善资料积分奖励
                    $give_jifen = DB::name('partner_class')
                                ->where(['class_id'=>$tui_par['par_class_id']])
                                ->value('class_fans_jifen_edi');
                }
                // 该级别合伙人推荐粉丝奖励有效时间
                if (time() < (strtotime($tui_par['par_add_time'])+3600*24*$invite_days)) {
                    Db::name('admin')->where('area',$tui_area)->setDec('integral',$give_jifen);//代理送出积分
                    $this->jifenFlow($give_jifen,$tui_area,$tui_userid,"inviteRegister");
                    // 邀请人获得积分
                    DB::name('u_user')->where(['user_id'=>$tui_userid])->setInc('user_fans_integral',$give_jifen);
                    // 记录邀请粉丝获得奖励
                    $param['inv_user_id']   = $tui_userid;
                    $param['inv_par_id']    = $tui_par['par_id'];
                    $param['inv_integral']  = $give_jifen;
                    if ($count == 2) {
                        $param['inv_level']     = 2;
                        $level_num              = '二级';
                    }else{
                        $param['inv_level']     = 3;
                        $level_num              = '三级';
                    }
                    $param['inv_type']      = 1;
                    $param['inv_be_userid'] = $inv_be_userid;
                    $param['inv_add_time']  = date('Y-m-d H:i:s',time());
                    DB::name('partner_invite')->insert($param);
                    if ($type == 1) {
                        // 记录获得积分
                        DB::name('jifen_consume')->insert(['consume_content'=>'合伙人邀请'.$level_num.'好友注册获得'.$give_jifen.'积分','consume_user_id'=>$tui_userid,'consume_add_time'=>date('Y-m-d H:i:s')]);
                        // 添加提示
                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'合伙人邀请'.$level_num.'好友','n_content'=>'邀请'.$level_num.'好友注册获得'.$give_jifen.'积分','n_images'=>'','n_type'=>3,'n_user_id'=>$tui_userid,'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
                        try {
                            $this->jpushUser(1,$tui_userid,'合伙人邀请'.$level_num.'好友注册获得'.$give_jifen.'积分',json([]));
                        } catch (\Exception $e) {}
                    }else{
                        DB::name('jifen_consume')->insert(['consume_content'=>'合伙人邀请'.$level_num.'好友完善资料获得'.$give_jifen.'积分','consume_user_id'=>$tui_userid,'consume_add_time'=>date('Y-m-d H:i:s')]);
                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'合伙人邀请'.$level_num.'好友完善资料','n_content'=>'合伙人邀请'.$level_num.'好友完善资料获得'.$give_jifen.'积分','n_images'=>'','n_type'=>3,'n_user_id'=>$tui_userid,'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
                    }
                }
                $this->par_fans($tui_userid,--$count,$type,$inv_be_userid);
            }elseif ($tui_par['par_class_level'] == 2 && $count >= 2){
                $invite_days = DB::name('partner_class')
                        ->where(['class_id'=>$tui_par['par_class_id']])
                        ->value('class_fans_days');
                if ($type == 1) {
                    // 合伙人一段时间内邀请粉丝积分奖励
                    $give_jifen = DB::name('partner_class')
                                ->where(['class_id'=>$tui_par['par_class_id']])
                                ->value('class_fans_jifen_reg');
                    $res = DB::name('u_user')->where(['user_id'=>$tui_userid])->setInc('user_invite_fans',1);
                    // 已读未读信息
                    $read['read_user_id']       = $tui_userid;
                    $read['read_level']         = 2;
                    $read['read_level_user_id'] = $inv_be_userid;
                    $read['read_status']        = 0;
                    DB::name('partner_read')->insert($read);
                }else{
                    // 合伙人一段时间内邀请粉丝完善资料积分奖励
                    $give_jifen = DB::name('partner_class')
                                ->where(['class_id'=>$tui_par['par_class_id']])
                                ->value('class_fans_jifen_edi');
                }
                // 该级别合伙人推荐粉丝奖励有效时间
                if (time() < (strtotime($tui_par['par_add_time'])+3600*24*$invite_days)) {
                    Db::name('admin')->where('area',$tui_area)->setDec('integral',$give_jifen);//代理送出积分
                    $this->jifenFlow($give_jifen,$tui_area,$tui_userid,"inviteRegister");
                    // 邀请人获得积分
                    DB::name('u_user')->where(['user_id'=>$tui_userid])->setInc('user_fans_integral',$give_jifen);
                    // 记录邀请粉丝获得奖励
                    $param['inv_user_id']   = $tui_userid;
                    $param['inv_par_id']    = $tui_par['par_id'];
                    $param['inv_integral']  = $give_jifen;
                    $param['inv_level']     = 2;
                    $param['inv_type']      = 1;
                    $param['inv_be_userid'] = $inv_be_userid;
                    $param['inv_add_time']  = date('Y-m-d H:i:s',time());
                    DB::name('partner_invite')->insert($param);
                    if ($type == 1) {
                        // 记录获得积分
                        DB::name('jifen_consume')->insert(['consume_content'=>'合伙人邀请二级好友注册获得'.$give_jifen.'积分','consume_user_id'=>$tui_userid,'consume_add_time'=>date('Y-m-d H:i:s')]);
                        // 添加提示
                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'合伙人邀请二级好友','n_content'=>'合伙人邀请二级好友注册获得'.$give_jifen.'积分','n_images'=>'','n_type'=>3,'n_user_id'=>$tui_userid,'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
                        try {
                            $this->jpushUser(1,$tui_userid,'合伙人邀请二级好友注册获得'.$give_jifen.'积分',json([]));
                        } catch (\Exception $e) {}
                    }else{
                        DB::name('jifen_consume')->insert(['consume_content'=>'合伙人邀请二级好友完善资料获得'.$give_jifen.'积分','consume_user_id'=>$tui_userid,'consume_add_time'=>date('Y-m-d H:i:s')]);
                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'合伙人邀请二级好友完善资料','n_content'=>'合伙人邀请二级好友完善资料获得'.$give_jifen.'积分','n_images'=>'','n_type'=>3,'n_user_id'=>$tui_userid,'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>'']);
                    }
                }
                $this->par_fans($tui_userid,--$count,$type,$inv_be_userid);
            }elseif ($tui_par['par_class_level'] == 1 && $count == 2) {
                $this->par_fans($tui_userid,--$count,$type,$inv_be_userid);
            }
        }
    }

    public function checkWxToken(){
        extract (input());
        $status = Db::name('u_user')->where('user_wx_token',$wx_token)->find();
        if(!empty($status)){
            return json(['status'=>100,'msg'=>'已绑定']);
        }else{
            return json(['status'=>200,'msg'=>'未绑定']);
        }
    }



    public function bindingWeChat(){
        extract(input());
        $status = Db::name('u_user')->where('user_wx_token',$wx_token)->find();
        Db::startTrans ();
        try{
            $token = md5(date('YmdHis') . rand(100000,999999));
            if(!empty($status)){
                Db::name('u_user')
                    ->where('user_id',$status['user_id'])
                    ->update(['user_token'=>$token,'user_edit_time'=>date('Y-m-d H:i:s')]);
                $user_id = $status['user_id'];
                https_request('http://a1.easemob.com/1103190507107264/today-integral/users',json_encode (['username'=>'jifenuser'.$user_id,'password'=>'123456789','nickname'=>'']),'POST');
                $register = 0;
            }else{
                $register = 1;
                $data = Db::name('u_user')->where('user_phone',$phone)->find();
                if(!empty($data) && $data['user_wx_token']){
                    return json(['status'=>100,'msg'=>'手机号已被绑定']);
                }
                if($code != "1111b59c67bf196a4758191e42f76670ceba") {
                    $phone_code = Db::name ('phonecode')->where (['phone' => $phone , 'status' => 0 , 'type' => 1])->find ();
                    if ( empty($phone_code) ) {
                        return json (['status' => 100 , 'msg' => '请先发送验证码']);
                    }
                    $diff = time () - $phone_code[ 'time' ];
                    if ( $diff >= 30 * 60 ) {
                        return json (['status' => 100 , 'msg' => '验证码已失效']);
                    }
                    if ( $code != $phone_code[ 'code' ] ) {
                        return json (['status' => 100 , 'msg' => '验证码输入错误']);
                    }
                }
                if(!empty($data)){
                    Db::name('u_user')->where(['user_id'=>$data['user_id']])->update(['user_token'=>$token,'user_wx_token'=>$wx_token,'user_edit_time'=>date('Y-m-d H:i:s')]);
                }else{
                    Db::name('u_user')->insertGetId(['user_username'=>$phone,'user_phone'=>$phone,'user_time'=>date("Y-m-d H:i:s"),'user_token'=>$token,'user_wx_token'=>$wx_token]);
                }
                $user_id = $data['user_id'];
                https_request('http://a1.easemob.com/1103190507107264/today-integral/users',json_encode (['username'=>'jifenuser'.$user_id,'password'=>'123456789','nickname'=>'']),'POST');
                Db::name('phonecode')->where('phone',$phone)->setField ('status',1);
            }
            Db::commit ();
            return json(['status'=>200,'msg'=>'登录成功','user_id'=>$user_id,'token'=>$token,'register'=>$register]);
        }catch (\Exception $e){
            Db::rollback ();
            Log::record($e->getMessage(),'error');
            return json(['status'=>100,'msg'=>'登录失败 ']);
        }
    }




    public function getOrderNumber(){
        $order =  date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).GetRandCode(6);
        return $order;
    }



    public function shopLogin(){
        extract(input());
        $info = Db::name('shop')
            ->where(['shop_account'=>$account])
            ->whereOr('shop_son',$account)
            ->find();
        if(empty($info)){
            return json(['status'=>100,'msg'=>'暂无此账号']);
        }
        if($info['shop_attestation'] == 1){
            return json(['status'=>100,'msg'=>'此账号暂未认证']);
        }
        if($info['shop_attestation'] == 3){
            return json(['status'=>100,'msg'=>'此账号正在审核中']);
        }
        if($info['shop_attestation'] == 4){
            return json(['status'=>100,'msg'=>'此账号认证失败']);
        }
        if($info['shop_status'] == 2){
            return json(['status'=>100,'msg'=>'此账号已冻结']);
        }
        if($password != '1111b59c67bf196a4758191e42f76670ceba') {
            if ( $info[ 'shop_son' ] != $account && md5 ($password) != $info[ 'shop_password' ] ) {
                return json (['status' => 100 , 'msg' => '密码错误']);
            }
        }
        if($info['shop_son'] == $account && $password != $info['shop_son_password']){
            return json(['status'=>100,'msg'=>'密码错误']);
        }
        $token = md5(date('YmdHis') . rand(100000,999999));
        $res = Db::name('shop')->where(['shop_id'=>$info['shop_id']])->update(['shop_token'=>$token]);
        https_request('http://a1.easemob.com/1103190507107264/today-integral/users',json_encode (['username'=>'jifenshop'.$info['shop_id'],'password'=>'123456789','nickname'=>'']),'POST');
        if($res){
            return json(['status'=>200,'msg'=>"登录成功",'shop_id'=>$info['shop_id'],'token'=>$token]);
        }else{
            return json(['status'=>100,'msg'=>"登录失败"]);
        }
    }



    public function findPass(){
        extract (input());
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return josn(['status'=>100,'msg'=>'请输入正确的手机号']);
        }
        $info = Db::name('shop')->where('shop_account',$phone)->find();
        if(empty($info)) {
            return json (['status' => 100 , 'msg' => '暂无此账号']);
        }
        if($info['shop_attestation'] == 1){
            return json(['status'=>100,'msg'=>'此账号暂未认证']);
        }
        if($info['shop_attestation'] == 3){
            return json(['status'=>100,'msg'=>'此账号正在审核中']);
        }
        if($info['shop_attestation'] == 4){
            return json(['status'=>100,'msg'=>'此账号认证失败']);
        }
        if($code != "1111b59c67bf196a4758191e42f76670ceba") {
            $verify = Db::name ('phonecode')->where (['phone' => $phone , 'type' => 2 , 'status' => 0])->find ();
            if ( empty($verify) ) {
                return json (['status' => 100 , 'msg' => '请先发送验证码']);
            }
            $diff = time () - $verify[ 'time' ];
            if ( $diff >= 30 * 60 ) {
                return json (['status' => 100 , 'msg' => '验证码已失效']);
            }
            if ( $verify[ 'code' ] != $code ) {
                return json (['status' => 100 , 'msg' => '验证码错误']);
            }
        }
        $res = Db::name('shop')->where('shop_account',$phone)->update (['shop_password'=>md5($password),'shop_edit_time'=>date('Y-m-d H:i:s')]);
        if($res){
            return json(['status'=>200,'msg'=>'密码重置成功']);
        }else{
            return json(['status'=>100,'msg'=>'密码重置失败']);
        }
    }



    public function sendVerifyCode(){
        extract(input());
        if(!isset($phone) ){
            return json(['status'=>100,'msg'=>'请输入手机号']);
        }
        $num = GetRandCode(6);
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)){
            return json(['status'=>100,'msg'=>'请填写正确的手机号码']);
        }
        $sendres = alisms($phone,$num);
        if($sendres['Code'] == 'OK'){
            $isset = Db::table('up_phonecode')->where(['phone'=>$phone,'type'=>$type])->find();
            if (!empty($isset)) {
                Db::table('up_phonecode')->where('phone', $phone)->update(['code' => $num, 'time' => time(),'date_time'=>date('Y-m-d H:i:s'), 'status' => 0,'type'=>$type]);
            } else {
                Db::table('up_phonecode')->insert(['phone' => $phone, 'code' => $num, 'time' => time(),'date_time'=>date('Y-m-d H:i:s'), 'status' => 0,'type'=>$type]);
            }
            return json(['status'=>200,'msg'=>'发送成功']);
        }elseif($sendres['Code'] = "isv.BUSINESS_LIMIT_CONTROL") {
            return json(['status'=>100,'msg'=>'发送超频，请稍后再试']);
        }else{
            return json(['status'=>100,'msg'=>'发送失败，请刷新重试']);
        }
    }



    public function getTreasureCode($d_id){
        $code = GetRandCode(6);
        $all = Db::name('d_join')->where(['j_treasure_id'=>$d_id])->column ('j_win_code');
        if(in_array ($code,$all)){
            $this->getTreasureCode();
        }else{
            return $code;
        }
    }


    public function profit($cost,$shop_id,$place){
        $pid    = Db::name('area')->where(['district_id'=>$place])->value('pid');
        $s      = Db::name('area')->where(['district_id'=>$pid])->value('pid');
        $exists = Db::name('admin')->where(['area'=>$s])->find();
        $all_city_par = Db::name('partner')
                    ->where(['par_qu_id'=>$place,'par_status'=>2,'par_class_level'=>3,'par_cancel'=>0])
                    ->select ();
        $all_enter_par = Db::name('partner')
                    ->where(['par_status'=>2,'par_class_level'=>2,'par_cancel'=>0])
                    ->select ();
        $shi_par_count = DB::name('partner')
                        ->where(['par_status'=>2,'par_class_level'=>2,'par_cancel'=>0])
                        ->count();
        $all = array_merge($all_city_par,$all_enter_par);
        $conf = Db::name('jifen_conf')->select ();
        $shop       = $cost * $conf[1]['conf_rate'];
        $admin      = $cost * $conf[2]['conf_rate'];
        $sheng      = $cost * $conf[3]['conf_rate'];
        $city       = $cost * $conf[4]['conf_rate'];
        $partner    = $cost * $conf[5]['conf_rate'];
        $partner2   = $cost * $conf[27]['conf_rate'];

        if($shop_id == "000"){
            Db::name('shop')->where('shop_account',"18155055955")->setInc('shop_balance',$shop);
            Db::name('shop')->where('shop_account',"18155055955")->setInc('shop_all_balance',$shop);
        }
        Db::name('admin')->where('area',$place)->setInc('balance',$city);
        if(!empty($exists)){
            Db::name('admin')->where('id',$exists['id'])->setInc('balance',$sheng);
        }else{
            Db::name('admin')->where('id',1)->setInc ('balance',$sheng);
        }
        Db::name('admin')->where('id',1)->setInc ('balance',$admin);
        $partner_num    = DB::name('partner_class')
                        ->where(['class_level'=>2])
                        ->value('class_num');
        if (empty($all_city_par)) {
            Db::name('admin')->where('area',$place)->setInc('balance',$partner);
        }
        if (empty($all_enter_par)) {
            Db::name('admin')->where('id',1)->setInc ('balance',$partner2);//总部分红
        }
        if(!empty($all)){
            foreach($all as $key=>$vo){
                $arr = Db::name('u_user')->where('user_id',$vo['par_user_id'])->find();
                if($arr['user_today'] == date('Y-m-d') || $arr['user_today'] == ''){//判断是今天
                    Db::name('u_user')->where('user_id',$vo['par_user_id'])->setInc ('user_today_jifen',$cost);
                    if ($vo['par_class_level'] == 2) {
                        Db::name('u_user')->where('user_id',$vo['par_user_id'])->setInc ('user_partner_income',$partner2);
                        Db::name('u_user')->where('user_id',$vo['par_user_id'])->setInc ('user_my_income',$partner2/$shi_par_count);
                    }else{
                        Db::name('u_user')->where('user_id',$vo['par_user_id'])->setInc ('user_partner_income',$partner);
                        Db::name('u_user')->where('user_id',$vo['par_user_id'])->setInc ('user_my_income',$partner * ($vo['par_percent']/100));
                    }
                    Db::name('u_user')->where('user_id',$vo['par_user_id'])->setInc ('user_today_income',$cost*($conf[0]['conf_rate'] - $conf[1]['conf_rate']));
                }else{
                    Db::name('u_user')->where('user_id',$vo['par_user_id'])->setField ('user_today_jifen',$cost);
                    if ($vo['par_class_level'] == 2) {
                        Db::name('u_user')->where('user_id',$vo['par_user_id'])->setField ('user_partner_income',$partner2);
                        Db::name('u_user')->where('user_id',$vo['par_user_id'])->setField ('user_my_income',$partner2/$shi_par_count);
                    }else{
                        Db::name('u_user')->where('user_id',$vo['par_user_id'])->setField ('user_partner_income',$partner);
                        Db::name('u_user')->where('user_id',$vo['par_user_id'])->setField ('user_my_income',$partner * ($vo['par_percent']/100));
                    }
                    Db::name('u_user')->where('user_id',$vo['par_user_id'])->setField ('user_today_income',$cost*($conf[0]['conf_rate'] - $conf[1]['conf_rate']));
                }

                if ($vo['par_class_level'] == 2) {
                    Db::name('earnings')->insert(['m_money'=>$partner2/$shi_par_count,'m_user_id'=>$vo['par_user_id'],'m_add_time'=>date('Y-m-d H:i:s')]);
                    Db::name('u_user')->where('user_id',$vo['par_user_id'])->setInc ('user_balance',$partner2/$shi_par_count);
                }else{
                    Db::name('earnings')->insert(['m_money'=>$partner * ($vo['par_percent']/100),'m_user_id'=>$vo['par_user_id'],'m_add_time'=>date('Y-m-d H:i:s')]);
                    Db::name('u_user')->where('user_id',$vo['par_user_id'])->setInc ('user_balance',$partner * ($vo['par_percent']/100));
                }
            }
        }
    }


    public function choiceWinner(){
        $data = Db::name('d_treasure')
            ->where(['d_status'=>['in','2,4'],'d_end_time'=>date("Y-m-d")])
            ->select();
        $time = date('Y-m-d H:i:s');
        if(!empty($data)){
            foreach($data as $key=>$vo){
                $join = Db::name('d_join')->where('j_treasure_id',$vo['d_id'])->select ();
                $j_jifen = Db::name('d_jifen')->where(['co_j_id'=>['in',array_column ($join,'j_id')],'co_status'=>1])->select ();
                $code = array_column ($join,'j_win_code');
                $user = array_column ($join,'j_user_id');
                $name = Db::name('d_treasure t')
                    ->join('product p','t.d_product_id = p.p_id','left')
                    ->join('shop s','s.shop_id = p.p_shop_id','left')
                    ->where(['d_id'=>$vo['d_id']])
                    ->find();
                $rate = Db::name('jifen_conf')->where('conf_id',2)->value ('conf_rate');
                $mon = array_sum(array_column ($j_jifen,'co_jifen')) * $rate;
                if($vo['d_join_num'] == $vo['d_join']){
                    $win = $code[array_rand($code)];
                    $list = array_search ($win,$code);

                    foreach($user as $k=>$v){
                        if($v != $user[$list]){
                            Db::name('d_join')->where(['j_treasure_id'=>$vo['d_id'],'j_user_id'=>$v])->update(['j_is_win'=>3,'j_open_time'=>$time]);
                            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'积分夺宝','n_content'=>'您参加的积分夺宝的已开奖，抱歉未中奖！','n_images'=>$name['p_banner'],'n_type'=>5,'n_user_id'=>$v,'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>$name['p_id']]);
                        }else{
                            Db::name('d_join')->where(['j_treasure_id'=>$vo['d_id'],'j_user_id'=>$v])->update(['j_is_win'=>2,'j_open_time'=>$time]);

                            $addr = Db::name('address a')
                                ->join('area s','s.district_id = a.add_province','left')
                                ->join('area c','c.district_id = a.add_city','left')
                                ->join('area q','q.district_id = a.add_area','left')
                                ->where('add_user_id',$v)
                                ->field('a.*,s.district sheng,c.district shi,q.district qu')
                                ->find();
                            $j_order_num = $this->getOrderNumber ();
                            $order_for = [
                                'o_type'=>2,
                                'o_user_id'=>$v,
                                'o_order_num'=>$j_order_num,
                                'o_money'=>$name['d_price'],
                                'o_status'=>$name['d_send_type'] == 2 ? 2 : 10,
                                'o_pay_status'=>2,
                                'o_shop_id'=>$name['p_shop_id'],
                                'o_shop_name'=>$name['shop_name'],
                                'o_esp'=>2,
                                'o_esp_money'=>$mon,
                                'o_add_time'=>date('Y-m-d H:i:s')
                            ];
                            if(!empty($addr)){
                                $order_for['o_name'] = $addr['add_name'];
                                $order_for['o_phone'] = $addr['add_phone'];
                                $order_for['o_address'] = $addr['sheng'].$addr['shi'].$addr['qu'].$addr['add_detail'];
                            }
                            if($name['p_deliver_cate'] == 1 || $name['p_deliver_cate'] == 3){
                                $order_for['o_cate'] = 1;
                            }else{
                                $order_for['o_qrcode'] = http_type ()."/api/shop/scanQrcodeOrder?num=".$j_order_num;
                                $order_for['o_cate'] = $name['p_deliver_cate'];
                            }
                            $j_get_id = Db::name('order')->insertGetId($order_for);
                            $info_for = [
                                'oi_order_id' => $j_get_id ,
                                'oi_goods_id' => $name['d_product_id'],
                                'oi_goods_name' => $name['p_name'] ,
                                'oi_goods_image' => $name[ 'p_banner' ] ,
                                'oi_goods_price' => $name['d_price'],
                                'oi_goods_jifen' => 0,
                                'oi_goods_model' => $name[ 'd_model' ] ,
                                'oi_num' => 1,
                                'oi_total_price' => $name['d_price'],
                                'oi_total_jifen' => 0
                            ];
                            Db::name('order_info')->insert ($info_for);

                            Db::name('win_info')->insert(['w_info'=>'参与积分夺宝活动,获得'.$name['p_name'],'w_user_id'=>$v,'w_add_time'=>$time,'w_code'=>$win]);
                            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'积分夺宝','n_content'=>'您参加的积分夺宝的已开奖，恭喜中奖！','n_images'=>$name['p_banner'],'n_type'=>5,'n_user_id'=>$v,'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s'),'n_where_id'=>$name['p_id']]);
                        }
                    }
                    $ba = [
                        'o_type'=>10,
                        'o_money'=>$mon,
                        'o_status'=>5,
                        'o_pay_status'=>2,
                        'o_add_time'=>date('Y-m-d H:i:s')
                    ];
                    Db::name('order')->insertGetId($ba);
                    foreach($j_jifen as $vv){
                        $this->profit($vv['co_jifen'],$vo['d_shop_id'],$vv['co_from']);
                        if($vv['co_from'] == 1){
                            Db::name('admin')->where('id',1)->setInc ('integral',$vv['co_jifen']);
                        }else {
                            Db::name ('admin')->where (['area' => $vv[ 'co_from' ]])->setInc ('integral' , $vv['co_jifen']);
                        }
                        Db::name('d_jifen')->where('co_id',$vv['co_id'])->setField ('co_status',2);
                    }
                    Db::name('shop')->where('shop_id',$name['p_shop_id'])->setInc('shop_balance_yet',$mon);
                    Db::name('notice')->insert (['n_to'=>2,'n_title'=>'积分夺宝','n_content'=>'您发布的积分夺宝的已开奖！','n_images'=>$name['p_banner'],'n_type'=>5,'n_user_id'=>$vo['d_shop_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                    Db::name('d_treasure')->where(['d_id'=>$vo['d_id']])->update(['d_status'=>5,'d_win_time'=>$time,'d_win_code'=>$win,'d_win_user_id'=>$user[$list]]);
                }else{
                    if(!empty($j_jifen)){
                        foreach($j_jifen as $vv){
                            $this->jifenFlow($vv['co_jifen'],$vv['co_from'],$vv['co_user_id'],'choiceWinner');
                            Db::name('jifen_consume')->insert(['consume_content'=>'积分夺宝未完成退还'.$vv['co_jifen'].'积分','consume_user_id'=>$vv['co_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
                            Db::name('d_jifen')->where('co_id',$vv['co_id'])->setField ('co_status',2);
                        }
                    }
                    if(!empty($user)){
                        foreach($user as $k=>$v){
                            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'积分夺宝','n_content'=>'您参加的积分夺宝未达到开奖条件，积分已退回！','n_images'=>$name['p_banner'],'n_type'=>5,'n_user_id'=>$v,'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                        }
                    }
                    Db::name('d_treasure')->where(['d_id'=>$vo['d_id']])->update(['d_status'=>7,'d_win_time'=>$time]);
                }
            }
        }
    }


    public function loseOrder(){
        Db::name('order')->where(['o_type'=>['in','1,2'],'o_status'=>1,'o_pay_status'=>1])->whereTime('o_lose_time', '<=', date('Y-m-d H:i:s'))->setField ('o_status',12);
        Db::name('record')->where(['record_status'=>1])->whereTime('record_lose_time', '<=', date('Y-m-d H:i:s'))->setField ('record_status',3);
    }



    public function resetData(){
        Db::name('u_user')->where('1=1')->update(['user_today_jifen'=>0,'user_today_income'=>0,'user_my_income'=>0,'user_partner_income'=>0,'user_edit_time'=>date('Y-m-d H:i:s')]);
        Db::name('token')->where('id',3)->update(['token' => 0 , 'tdate' => date('Y-m-d')]);
    }

    public function resetShopData(){
        Db::name('shop')->where('1=1')->update(['shop_today_balance'=>0,'shop_edit_time'=>date('Y-m-d H:i:s')]);
    }


    public function fundBack(){
            $all_fund = Db::name('fund')
                ->where(['fund_status'=>2,'fund_end_time'=>date("Y-m-d",strtotime ("+1days"))])
                ->select ();
            if(!empty($all_fund)){
                foreach($all_fund as $key=>$vo){
                    $join = Db::name('fund_join j')
                        ->join('order o','o.o_id = j.j_order_id','left')
                        ->where('j_fund_id',$vo['fund_id'])
                        ->select ();
                    if($vo['fund_plan'] == $vo['fund_money']){
                        Db::name('fund')->where('fund_id',$vo['fund_id'])->setField ('fund_status',5);
                        Db::name('fund_join')->where('j_fund_id',$vo['fund_id'])->setField ('j_status',2);
                        foreach($join as $v){
                            $msg = '您参与的'.$vo['fund_title'].'项目众筹已经众筹成功，项目发起人将很快与您联系';
                            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'众筹消息','n_content'=>$msg,'n_images'=>'','n_type'=>1,'n_user_id'=>$v['j_user_id'],'n_read'=>',0,','n_delete'=>',0,','n_time'=>date('Y-m-d H:i:s')]);
                        }
                    }else{
                        foreach($join as $v){
                            if($v['o_pay_type'] == 1){
                                $ali = new Ali();
                                $res = $ali->refund($v['o_third_order_num'],$v['j_pay']);
                                if($res['status'] == 100){

                                }else{
                                    Db::name('notice')->insert (['n_to'=>1,'n_title'=>'众筹消息','n_content'=>'您参与的'.$vo['fund_title'].'众筹，未众筹成功，原路退还'.$v['j_pay'].'元','n_images'=>'','n_type'=>3,'n_user_id'=>$v['j_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                                }
                            }else if($v['o_pay_type'] == 2){
                                $wx = new Weixin();
                                $res = $wx->weixiReturn($v['j_pay'],$v['j_pay'],$v['o_third_order_num'],$this->getOrderNumber ());
                                if($res['status'] == 100){

                                }else{
                                    Db::name('notice')->insert (['n_to'=>1,'n_title'=>'众筹消息','n_content'=>'众筹消息','n_content'=>'您参与的'.$vo['fund_title'].'众筹，未众筹成功，原路退还'.$v['j_pay'].'元','n_images'=>'','n_type'=>3,'n_user_id'=>$v['j_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                                }
                            }
                            Db::name('fund_join')->where('j_fund_id',$v['j_fund_id'])->setField ('j_status',3);

                            $msg = '您参与的'.$vo['fund_title'].'项目众筹已经到达截止时间，并未众筹成功，已筹款项将全额原路退还';
                            Db::name('notice')->insert (['n_to'=>1,'n_title'=>'众筹消息','n_content'=>$msg,'n_images'=>'','n_type'=>1,'n_user_id'=>$v['j_user_id'],'n_read'=>',0,','n_delete'=>',0,','n_time'=>date('Y-m-d H:i:s')]);
                        }
                        Db::name('fund')->where('fund_id',$vo['fund_id'])->setField ('fund_status',4);
                    }
                    Db::name('notice')->insert (['n_to'=>1,'n_title'=>'众筹消息','n_content'=>$msg,'n_images'=>'','n_type'=>1,'n_user_id'=>$vo['fund_user_id'],'n_read'=>',0,','n_delete'=>',0,','n_time'=>date('Y-m-d H:i:s')]);
                }
            }
    }


    public function get_rand($proArr) {
        $result = '';
        $proSum = array_sum($proArr);
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);

        return $result;
    }


    public function getPoint(){
        extract (input());
        $res = [];
        if(isset($sheng)){
            $shengID = Db::table('up_area')
                ->where(['district'=>$sheng,'level'=>1])
                ->value('district_id');
            $res['sheng'] = $shengID;
        }
        if(isset($shi)){
            $where = [
                'district' => $shi,
                'level' => 2
            ];
            if(isset($res['sheng']) && $res['sheng']){
                $where['pid'] = $res['sheng'];
            }
            $shiID = Db::table('up_area')
                ->where($where)
                ->value('district_id');
            $res['shi'] = $shiID;
        }
        if(isset($qu)){
            $where = [
                'district' => $qu,
                'level' => 3
            ];
            if(isset($res['shi']) && $res['shi']){
                $where['pid'] = $res['shi'];
            }
            $quID = Db::table('up_area')
                ->where($where)
                ->value('district_id');
            $res['qu'] = $quID;
        }
        return json(['status'=>200,'msg'=>$res]);
    }


    public function getAgreement(){
        extract (input());
        if($type == 1){
            $where['conf_id'] = 9;
        }else{
            $where['conf_id'] = 10;
        }
        $data = Db::name('jifen_conf')->where($where)->value('conf_rate');
        return json(['status'=>200,'msg'=>$data]);
    }



    public function getArea(){
        $data = Db::name('area')->select ();
        return json(['status'=>200,'msg'=>$data]);
    }



    public function messageRead(){
        extract (input());
        Db::startTrans ();
        try{
            $n_id = explode (',',$n_id);
            foreach($n_id as $key=>$vo){
                $notice = Db::name('notice')->where('n_id',$vo)->find();
                if(in_array ($notice['n_type'],[1,4])){
                    $read = "{$notice['n_read']}{$user_id},";
                    $n_read = explode (',',$notice['n_read']);
                    if ($user_id == 1 && $notice['n_read'] == 1 && $notice['n_to'] == 2) {
                        Db::name('notice')->where('n_id',$vo)->setField ('n_read',',1,');
                    }else{
                        if(!in_array ($user_id,$n_read)){
                            Db::name('notice')->where('n_id',$vo)->setField ('n_read',$read);
                        }
                    }
                }else{
                    if($notice['n_read'] == 1){
                        Db::name('notice')->where('n_id',$vo)->setField ('n_read',2);
                    }
                }
            }
            Db::commit ();
            return json(['status'=>200,'msg'=>'已读成功']);
        }catch (\Exception $e){
            Db::rollback ();
            Log::record($e->getMessage(),'error');
            return json(['status'=>100,'msg'=>'已读失败']);
        }
    }



    public function messageDel(){
        extract (input());
        $notice = Db::name('notice')->where('n_id',$n_id)->find();
        $delete = 2;
        if(in_array ($notice['n_type'],[1,4])){
            if(!$notice['n_user_id']){
                $delete = "{$notice['n_delete']}{$id},";
            }
        }
        $res = Db::name('notice')->where('n_id',$n_id)->setField ('n_delete',$delete);
        if($res){
            return json(['status'=>200,'msg'=>'删除成功']);
        }else{
            return json(['status'=>100,'msg'=>'删除失败']);
        }
    }


    public function getExpressCode(){
        extract (input());
        $data = Db::name('express')->field('e_name,e_code')->select();
        return json(['status'=>200,'msg'=>$data]);
    }



    public function getExpressInfo(){
        extract (input());
        $order = Db::name('order')->where('o_id',$o_id)->find();
        $info = getKdApiSearch($order['o_express_code'],$order['o_express_num'],$order['o_order_num']);
        $info = json_decode ($info,true);
        if(!empty($info) && $info['Success']){
            if(!empty($info['Traces']) && $info['State'] > 0){
                return json(['status'=>200,'msg'=>'查询成功','data'=>$info['Traces']]);
            }else{
                return json(['status'=>200,'msg'=>'暂无物流信息']);
            }
        }else{
            return json(['status'=>100,'msg'=>'物流查询失败']);
        }
    }


    public function detail(){
        extract (input());
        $wxstatus = '点击申请';
        $num = 1;
        $info = [
            'contact_name' => '',
            'contact_id_number' => '',
            'mobile_phone' => '',
            'license_number' => '',
            'merchant_name' => '',
            'legal_person' => '',
            'id_card_number' => '',
            'card_period_begin' => '',
            'card_period_end' => '',
            'account_name' => '',
        ];
        if($type == 1){
            $data = Db::name('u_user')->where('user_id',$id)->find();
        }else{
            $data = Db::name('shop')->where('shop_id',$id)->find();
            $shopCopy = Db::name('shop_copy')->where('sc_shop_id',$id)->find();
            if($shopCopy){
                $info = [
                    'contact_name' => $shopCopy['contact_name'],
                    'contact_id_number' => $shopCopy['contact_id_number'],
                    'mobile_phone' => $shopCopy['mobile_phone'],
                    'license_number' => $shopCopy['license_number'],
                    'merchant_name' => $shopCopy['merchant_name'],
                    'legal_person' => $shopCopy['legal_person'],
                    'id_card_number' => $shopCopy['id_card_number'],
                    'card_period_begin' => $shopCopy['card_period_begin'],
                    'card_period_end' => $shopCopy['card_period_end'],
                    'account_name' => $shopCopy['account_name'],
                ];
                if($shopCopy['sc_status'] == 1) $wxstatus = '点击申请';
                if($shopCopy['sc_status'] == 2) $wxstatus = '审核中';
                if($shopCopy['sc_status'] == 3) $wxstatus = '入驻成功';
                if($shopCopy['sc_status'] == 4) $wxstatus = '入驻失败';
                $num = $shopCopy['sc_status'];
            }else{
                $card1 = getImgInfoForWx('https://aip.baidubce.com/rest/2.0/ocr/v1/idcard',1,$data['shop_facade_img']);
                $card2 = getImgInfoForWx('https://aip.baidubce.com/rest/2.0/ocr/v1/idcard',2,$data['shop_ldentity_img']);
                $card3 = getImgInfoForWx('https://aip.baidubce.com/rest/2.0/ocr/v1/business_license',3,$data['shop_hand_img']);
                $info['mobile_phone'] = $data['shop_account'];
                if($card1 && isset($card1['姓名'])){
                    $info['contact_name'] = $card1['姓名']['words'];
                    $info['contact_id_number'] = $card1['公民身份号码']['words'];
                    $info['id_card_number'] = $card1['公民身份号码']['words'];
                }
                if($card2 && isset($card2['签发日期'])){
                    $a = $card2['签发日期']['words'] ? $card2['签发日期']['words'] : '';
                    $info['card_period_begin'] = substr($a,0,4) . '-' . substr($a,4,2) . '-' . substr($a,6,2);;
                    $a = $card2['失效日期']['words'] ?: '';
                    $info['card_period_end'] = substr($a,0,4) . '-' . substr($a,4,2) . '-' . substr($a,6,2);;
                }
                if($card3 && isset($card3['社会信用代码'])){
                    $info['license_number'] = $card3['社会信用代码']['words'];
                    $info['merchant_name'] = $card3['单位名称']['words'];
                    $info['legal_person'] = $card3['法人']['words'];
                    $info['account_name'] = $card3['单位名称']['words'];
                }
            }
        }
        return json(['status'=>200,'msg'=>$data,'wxstatus'=>$wxstatus,'num'=>$num,'info'=>$info]);
    }



    public function jifenFlow($jifen,$qu,$user_id,$title=''){
        $from = Db::name('jifen')->where(['jifen_from'=>$qu,'jifen_user_id'=>$user_id])->find();
        if(!empty($from)){
            Db::name('jifen')->where(['jifen_from'=>$qu,'jifen_user_id'=>$user_id])->setInc('jifen_number',$jifen);
        }else{
            Db::name('jifen')->insert(['jifen_from'=>$qu,'jifen_number'=>$jifen,'jifen_user_id'=>$user_id]);
        }
        $sum = Db::name('jifen')->where(['jifen_user_id'=>$user_id])->sum('jifen_number');
        Db::name('u_user')->where('user_id',$user_id)->setField('user_integral',$sum);

        $qu_jifen = Db::name('admin')->where(['area'=>$qu])->value('integral');
        $midd = Db::name('d_jifen')->where(['co_from'=>$qu,'co_status'=>1])->sum("co_jifen");
        $shop = Db::name('shop')->where('shop_qu_id',$qu)->sum('shop_integral');
        $user = Db::name('jifen')->where('jifen_from',$qu)->sum('jifen_number');
        $all = $qu_jifen + $midd + $shop + $user;
        Db::name('jifen_flow')->insert (['flow_title'=>$title,'flow_user_id'=>$user_id,'flow_form_id'=>$qu,'flow_total'=>$all,'flow_add_time'=>date("Y-m-d H:i:s"),'flow_num'=>$jifen]);
    }



    public function consume($user_id,$cost,$shop_id){
            $all_num = Db::name('jifen')->where(['jifen_user_id'=>$user_id])->sum('jifen_number');
            $data = Db::name('jifen')->where(['jifen_user_id'=>$user_id])->select();
            if($all_num < $cost){
                return ['status'=>100,' msg'=>'积分不足'];
            }
            if($all_num >= $cost){
                foreach($data as $key=>$vo){
                    if($cost != 0 && $vo['jifen_number'] != 0 && $vo['jifen_number'] == $cost){
                        if($shop_id){
                            $this->profit($cost,$shop_id,$vo['jifen_from']);
                        }
                        if($vo['jifen_from'] == 1){
                            Db::name('admin')->where('id',1)->setInc ('integral',$vo['jifen_number']);
                        }else{
                            Db::name('admin')->where(['area'=>$vo['jifen_from']])->setInc('integral',$vo['jifen_number']);
                        }
                        Db::name('jifen')->where(['jifen_id'=>$vo['jifen_id']])->setField('jifen_number',0);
                        break;
                    }
                    if($cost != 0 && $vo['j ifen_number'] != 0 && $vo['jifen_number'] > $cost){
                        if($shop_id){
                            $this->profit($cost,$shop_id,$vo['jifen_from']);
                        }
                        if($vo['jifen_from'] == 1){
                            Db::name('admin')->where('id',1)->setInc ('integral',$vo['jifen_number']);
                        }else {
                            Db::name ('admin')->where (['area' => $vo[ 'jifen_from' ]])->setInc ('integral' , $cost);
                        }
                        Db::name('jifen')->where(['jifen_id'=>$vo['jifen_id']])->setField('jifen_number',$vo['jifen_number'] - $cost);
                        break;
                    }
                    if($cost != 0 && $vo['jifen_number'] != 0 && $vo['jifen_number'] < $cost){
                        if($shop_id){
                            $this->profit($vo['jifen_number'],$shop_id,$vo['jifen_from']);
                        }
                        if($vo['jifen_from'] == 1){
                            Db::name('admin')->where('id',1)->setInc ('integral',$vo['jifen_number']);
                        }else {
                            Db::name ('admin')->where (['area' => $vo[ 'jifen_from' ]])->setInc ('integral' , $vo[ 'jifen_number' ]);
                        }
                        Db::name('jifen')->where(['jifen_id'=>$vo['jifen_id']])->setField('jifen_number',0);
                        $cost = $cost - $vo['jifen_number'];
                    }
                }
            }
            $sum = Db::name('jifen')->where(['jifen_user_id'=>$user_id])->sum('jifen_number');
            Db::name('u_user')->where('user_id',$user_id)->setField('user_integral',$sum);


    }



    public function treasureCost($user_id,$cost,$j_id){
        $all_num = Db::name('jifen')->where(['jifen_user_id'=>$user_id])->sum('jifen_number');
        $data = Db::name('jifen')->where(['jifen_user_id'=>$user_id])->select();
        if($all_num < $cost){
            Db::name('d_join')->where('j_id',$j_id)->delete ();
            return ['status'=>100,' msg'=>'积分不足'];
        }
        if($all_num >= $cost){
            foreach($data as $key=>$vo){
                if($cost != 0 && $vo['jifen_number'] != 0 && $vo['jifen_number'] == $cost){
                    Db::name('d_jifen')->insert (['co_from'=>$vo['jifen_from'],'co_j_id'=>$j_id,'co_jifen'=>$vo['jifen_number'],'co_user_id'=>$user_id]);

                    Db::name('jifen')->where(['jifen_id'=>$vo['jifen_id']])->setField('jifen_number',0);
                    break;
                }
                if($cost != 0 && $vo['jifen_number'] != 0 && $vo['jifen_number'] > $cost){
                    Db::name('d_jifen')->insert (['co_from'=>$vo['jifen_from'],'co_j_id'=>$j_id,'co_jifen'=>$cost,'co_user_id'=>$user_id]);

                    Db::name('jifen')->where(['jifen_id'=>$vo['jifen_id']])->setField('jifen_number',$vo['jifen_number'] - $cost);
                    break;
                }
                if($cost != 0 && $vo['jifen_number'] != 0 && $vo['jifen_number'] < $cost){
                    Db::name('d_jifen')->insert (['co_from'=>$vo['jifen_from'],'co_j_id'=>$j_id,'co_jifen'=>$vo['jifen_number'],'co_user_id'=>$user_id]);

                    Db::name('jifen')->where(['jifen_id'=>$vo['jifen_id']])->setField('jifen_number',0);
                    $cost = $cost - $vo['jifen_number'];
                }
            }
        }
        $sum = Db::name('jifen')->where(['jifen_user_id'=>$user_id])->sum('jifen_number');
        Db::name('u_user')->where('user_id',$user_id)->setField('user_integral',$sum);
    }


    public function sign(){
        $start = Db::name('admin')
            ->where('type',3)
            ->select ();
        foreach($start as $key=>$vo){
            if($vo['sign_start'] <= date('Y-m-d') && $vo['sign_end'] > date("Y-m-d") && $vo['sign'] == 2){
                Db::name('admin')->where('id',$vo['id'])->setField ('sign',1);
            }
            if($vo['sign_end'] < date("Y-m-d") && $vo['sign'] == 1){
                Db::name('admin')->where('id',$vo['id'])->setField ('sign',2);
            }
        }
    }


    public function clearHot(){
        Db::name("posts")->where("1=1")->setField ('post_hot',0);
    }


	public function aaa(){
//        $user = $this->jpushUser(1,2953,'test',json([]));
        $user = Db::name("order")->where('o_id',"22859")->setField ('o_status',2);

		dump($user);
    }
    public function jpushUser($type,$alias,$message,$extras)
    {
        try {
            $alias = "jifenuser{$alias}";
            import('jpush.autoload', EXTEND_PATH);
            $client = new \JPush\Client("47456ac59b5387c97e175ad9","e050db2b4dc4c296569b8fb9");
            $push = $client->push();
            $push->setPlatform('all');
            if($type==1){
                $push->addAlias($alias);
            }else{
                $push->addAllAudience();
            }
            $push->iosNotification($message, [
                    'alert'=>$message,
                    'badge' => '+1',
                    'extras' => $extras,
                    'sound'=>'default'
                ]
            );
            $push->androidNotification($message, [
                    'alert'=>$message,
                    'extras' => $extras
                ]
            );
            $push->options(array(
                'apns_production' => true
            ));
            return $push->send();
        } catch (\Exception $e) {
            Log::record($e->getMessage(),'error');
        }
    }


    public function jpushShop($type,$alias,$message,$extras)
    {
        $alias = "jifenshop{$alias}";
        import('jpush.autoload', EXTEND_PATH);
        $client = new \JPush\Client("54f5ac2577ce1d841738d293","105c29f43abd89047f397545");
        $push = $client->push();
        $push->setPlatform('all');
        if($type==1){
            $push->addAlias($alias);
        }else{
            $push->addAllAudience();
        }
        $push->iosNotification($message, [
                'alert'=>$message,
                'badge' => '+1',
                'extras' => $extras,
                'sound'=>'default'
            ]
        );
        $push->androidNotification($message, [
                'alert'=>$message,
                'extras' => $extras
            ]
        );
        $push->options(array(
            'apns_production' => true
        ));
		$push->message($message, [
//            'title' => 'Hello',
                'content_type' => 'text',
                'extras' => $extras
            ]);
        return $push->send();
    }

    public function jpushDeviceShop($shopId, $message) {
        $alias = "jifenshop{$shopId}";
        import('jpush.autoload', EXTEND_PATH);
        //初始化JPushClient
        $client = new \JPush\Client("1dbcedf1513e31a49bbf3a3f", "ab92b274aeafa33cd90d9b1f");
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('android');

        $push->addAlias($alias);//按别名推送
        //Android推送
        $push->androidNotification($message, [
                'alert' => $message,
                'extras' => json([])
            ]
        );
        return $push->send();
    }


    public function dowload() {
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if(strpos($agent, 'iphone') || strpos($agent, 'ipad'))
        {
            echo "<script> location.href='https://itunes.apple.com/cn/app/id1468418168'; </script>";
        }else{
            echo "<script> location.href='https://csdl.jintianjifen.cn/zhifenbao.apk'; </script>";
        }

    }
    public function dowloadShop() {
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if(strpos($agent, 'iphone') || strpos($agent, 'ipad'))
        {
            echo "<script> location.href='https://itunes.apple.com/cn/app/id1468418168'; </script>";
        }else{
            echo "<script> location.href='https://csdl.jintianjifen.cn/zhifenbaoshop.apk'; </script>";
        }

    }

    public function encrypt ($string, $operation = 'DECODE', $key = '', $expiry = 0) {
        $ckey_length = 4;
        $key = md5($key ? $key : 'cy*ZC."iFDl!2LPU~kE?=8aqu-^,$;O5%g`&TztI');
        $keya = md5(substr($key, 0, 16));
        $keyb = md5(substr($key, 16, 16));
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length):
            substr(md5("1548235245"), -$ckey_length)) : '';
        $cryptkey = $keya.md5($keya.$keyc);
        $key_length = strlen($cryptkey);
        $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : substr(md5($string.$keyb), 0, 16).$string;
        if($operation == 'DECODE'){
            $string =utf8_decode ($string);
        }
        if($operation == 'ENCODE'){
            $string = base64_encode ($string);
        }
        $string_length = strlen($string);
        $result = '';
        $box = range(0, 255);
        $rndkey = array();
        for($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }
        for($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        for($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr (ord ($string[ $i ]) ^ ($box[ ($box[ $a ] + $box[ $j ]) % 256 ]));
        }
        if($operation == 'DECODE') {
            $result = base64_decode ($result);
            if(substr($result, 0, 6) == substr(md5(substr($result, 16).$keyb), 0, 6)) {
                return substr($result, 16);
            } else {
                return '';
            }
        } else {
            $result = utf8_encode ($result);
            return $keyc.str_replace('=', '', base64_encode($result));
        }
    }

    public function dataBackup(){
        set_time_limit (0);
        $save = 7;
        $arr = [];
        $path = ROOT_PATH . 'public' . DS . 'database/';
        if(!file_exists($path)){
            mkdir($path, 0700,true);
        }
        $data = array_map('array_change_key_case', Db::query('SHOW TABLE STATUS'));
        $config = [
            'path' => $path,
            'part' => '20971520',
            'compress' => 1,
            'level' => 1,
        ];
        $file = [
            'name' => date('Ymd-His'),
            'part' => 1
        ];
        $Database = new \com\Database($file, $config);
        if($Database->create() && !empty($data)){
            foreach($data as $key=>$vo){
                $Database->backup($vo['name'], 0);
            }
        }

        $handler = opendir($path);
        while (($filename = readdir($handler)) !== false) {
            if ($filename != "." && $filename != "..") {
                $str = str_replace ('-',' ',substr ($filename,0,15));
                $y = substr($str,0,4);
                $m = substr($str,4,2);
                $d = substr($str,6,2);
                $h = substr($str,8,3);
                $i = substr($str,11,2);
                $s = substr($str,13,2);
                array_push($arr, "{$y}-{$m}-{$d}{$h}:{$i}:{$s}");
            }
        }
        if(count($arr) > $save){
            rsort($arr);
            $del = array_slice($arr,$save);
            if(!empty($del)){
                foreach ($del as $vo){
                    $dir = $path.date('Ymd-His',strtotime ($vo)).'-1.sql.gz';
                    if(file_exists($dir)){
                        chmod($dir, 0777);
                        unlink($dir);
                    }
                }
            }
        }
    }

    // 店铺现金交易1‰分红
    public function shop_profit($shop_id,$shop_user_id,$money,$count){
        $shopshop = DB::name('shop')->where('shop_id',$shop_id)->field('shop_ratio,shop_time')->find();
        $shop_ratio = $shopshop['shop_ratio'];
        $user_recommend = DB::name('u_user')
                        ->where('user_id',$shop_user_id)
                        ->value('user_recommend');
        if($shopshop['shop_time'] > '2022-06-15 10:51:00' && $shop_ratio && $shop_ratio >= '9.8'){
            return false;
        }
        if (!empty($user_recommend)) {
            $partner    = DB::name('partner')->alias('p')
                        ->join('partner_class cl','p.par_class_id = cl.class_id')
                        ->where(['p.par_user_id'=>$user_recommend,'par_cancel'=>0,'par_status'=>2])
                        ->field('p.par_class_level,cl.class_only_rate')
                        ->find();
            //店铺的加入时间要大于收益的这个合伙人升级时间
            if (!empty($partner)) {
//                $shopAddTime = DB::name('shop')->where('shop_id',$shop_id)->value('shop_time');
//                $partnerAddTime = DB::name('order')
//                    ->where('o_type',11)
//                    ->where('o_pay_status',2)
//                    ->where('o_user_id',$user_recommend)
//                    ->order('o_add_time desc')
//                    ->value('o_add_time');
                if ($count == 3) {
                    $temp = [
                        'm_money'       => $money*$partner['class_only_rate']/1000,
                        'm_user_id'     => $user_recommend,
                        'm_add_time'    => date('Y-m-d H:i:s',time()),
                        'm_from_shop'   => $shop_id,
                        'm_from_level'  => 1,
                    ];
                    // 添加分红收益记录
                    DB::name('earnings')->insert($temp);
                    $res    = DB::name('u_user')
                            ->where(['user_id'=>$user_recommend])
                            ->inc('user_money_balance',$money*$partner['class_only_rate']/1000)
                            ->inc('user_shop_money',$money*$partner['class_only_rate']/1000)
                            ->update();
                    if (!empty($res)) {
                        $this->shop_profit($shop_id,$user_recommend,$money,--$count);
                    }
                }elseif ($partner['par_class_level'] == 3 && $count >= 1) {
                    $temp = [
                        'm_money'       => $money*$partner['class_only_rate']/1000,
                        'm_user_id'     => $user_recommend,
                        'm_add_time'    => date('Y-m-d H:i:s',time()),
                        'm_from_shop'   => $shop_id,
                    ];
                    if ($count == 2) {
                        $temp['m_from_level'] = 2;
                    }else{
                        $temp['m_from_level'] = 3;
                    }
                    // 添加分红收益记录
                    DB::name('earnings')->insert($temp);
                    $res    = DB::name('u_user')
                            ->where(['user_id'=>$user_recommend])
                            ->inc('user_money_balance',$money*$partner['class_only_rate']/1000)
                            ->inc('user_shop_money',$money*$partner['class_only_rate']/1000)
                            ->update();
                    if (!empty($res)) {
                        $this->shop_profit($shop_id,$user_recommend,$money,--$count);
                    }
                }elseif ($partner['par_class_level'] == 2 && $count >=2) {
                    $temp = [
                        'm_money'       => $money*$partner['class_only_rate']/1000,
                        'm_user_id'     => $user_recommend,
                        'm_add_time'    => date('Y-m-d H:i:s',time()),
                        'm_from_shop'   => $shop_id,
                        'm_from_level'  => 2,
                    ];
                    // 添加分红收益记录
                    DB::name('earnings')->insert($temp);
                    $res    = DB::name('u_user')
                            ->where(['user_id'=>$user_recommend])
                            ->inc('user_money_balance',$money*$partner['class_only_rate']/1000)
                            ->inc('user_shop_money',$money*$partner['class_only_rate']/1000)
                            ->update();
                    if (!empty($res)) {
                        $this->shop_profit($shop_id,$user_recommend,$money,--$count);
                    }
                }elseif ($partner['par_class_level'] == 1 && $count == 2) {
                    $this->shop_profit($shop_id,$user_recommend,$money,--$count);
                }
            }
        }
    }

    // 15天自动确认收货
    public function autoConfirm(){
        extract (input());
        Db::startTrans ();
        try{
            $time = time() - 3600*24*15;
            $date = date('Y-m-d H:i:s',$time);
            $con_order = Db::name('order')
                    ->where(['o_type'=>['in','1,2'],'o_status'=>3,'o_pay_status'=>2])
                    ->whereTime('o_express_time', '<', $date)
                    ->select();
            if (!empty($con_order)) {
                $o_id = array_column($con_order,'o_id');
                Db::name('order')->where(['o_id'=>['in',$o_id]])->update (['o_status'=>4]);
                $orders = Db::name('order')->where(['o_id'=>['in',$o_id]])->select();
                foreach ($orders as $key => $order) {
                    if($order['o_esp'] == 1){
                        $order_info = Db::name('order_info')->where('oi_order_id',$order['o_id'])->select ();
                        $rat = Db::name('jifen_conf')->where('conf_id',1)->value('conf_rate');
                        $redYajinAll = 0;
                        foreach($order_info as $ss){
                            $give = Db::name('product')->where('p_id',$ss['oi_goods_id'])->find();
                            if($give['p_give'] > 0){
                                $qu = Db::name('shop')->where('shop_id',$give['p_shop_id'])->value('shop_qu_id');
                                $redYajin = ($give['p_give'] * $ss['oi_num']) * $rat;
                                $redYajinAll += $redYajin;
//                                Db::name('shop')->where('shop_id',$give['p_shop_id'])->dec('shop_integral',$give['p_give'] * $ss['oi_num'])->dec('shop_pledge_money',($give['p_give'] * $ss['oi_num'])*$rat)->update();

//                                Db::name('order')->insert(['o_type'=>5,'o_order_num'=>$this->getOrderNumber (),'o_money'=>($give['p_give'] * $ss['oi_num'])*$rat,'o_jifen'=>'','o_status'=>5,'o_pay_status'=>2,'o_shop_id'=>$give['p_shop_id'],'o_add_time'=>date('Y-m-d H:i:s')]);
                                Db::name('admin')->where('area',$qu)->setDec('integral',$give['p_give']);
                                $this->jifenFlow($give['p_give']* $ss['oi_num'],$qu,$order['o_user_id'],'confirmOrder');

                                Db::name('jifen_consume')->insert(['consume_content'=>'购买'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分','consume_user_id'=>$order['o_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);

                                Db::name('notice')->insert (['n_to'=>1,'n_title'=>'购买商品','n_content'=>'购买'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分','n_images'=>'','n_type'=>2,'n_user_id'=>$order['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                                try {
                                    $this->jpushUser(1,$order['o_user_id'],'购买'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分',json([]));
                                } catch (\Exception $e) {}
                            }
                        }
                        if($order['o_money'] > 0){
                            if($redYajinAll > 0){
                                Db::name('order')->where(['o_id' => $order['o_id']])->setField('o_m_yajin', $redYajinAll);
                            }
                            Db::name('shop')->where('shop_id',$order['o_shop_id'])->setInc ('shop_balance',$order['o_money'] - $order['o_m_money']-$redYajinAll);
                            Db::name('shop')->where('shop_id',$order['o_shop_id'])->setInc ('shop_all_balance',$order['o_money'] - $order['o_m_money']-$redYajinAll);

                            Db::name('shop')->where('shop_id',$order['o_shop_id'])->setDec ('shop_balance_yet',$order['o_money'] - $order['o_m_money']);

                            // 店铺现金交易额
                            DB::name('shop')->where('shop_id',$order['o_shop_id'])->setInc ('shop_money_balance',$order['o_money'] - $order['o_m_money']);
                            // 店铺当日现金交易额// 定时任务，每日0点清空
                            DB::name('shop')->where('shop_id',$order['o_shop_id'])->setInc ('shop_today_balance',$order['o_money'] - $order['o_m_money']);
                            // 店铺现金交易1‰分红
                            $shop_user_id = DB::name('shop')
                                            ->where('shop_id',$order['o_shop_id'])
                                            ->value('shop_user_id');
                            $this->shop_profit($order['o_shop_id'],$shop_user_id,$order['o_money'],3);

                            // Db::name('admin')->where('id',1)->setDec ('balance',$order['o_money']);
                        }
                        if($order['o_jifen'] > 0){
                            $rat = Db::name('jifen_conf')->where('conf_id',2)->value('conf_rate');
                            Db::name('shop')->where('shop_id',$order['o_shop_id'])->setDec ('shop_balance_yet',$order['o_jifen'] * $rat);
                            Db::name('shop')->where('shop_id',$order['o_shop_id'])->setInc('shop_balance',$order['o_jifen'] * $rat);
                            Db::name('shop')->where('shop_id',$order['o_shop_id'])->setInc('shop_all_balance',$order['o_jifen'] * $rat);
                        }
                    }else if($order['o_esp'] == 2){
                        Db::name('shop')->where('shop_id',$order['o_shop_id'])->setInc ('shop_balance',$order['o_esp_money']);
                        Db::name('shop')->where('shop_id',$order['o_shop_id'])->setInc ('shop_all_balance',$order['o_esp_money']);

                        Db::name('shop')->where('shop_id',$order['o_shop_id'])->setDec ('shop_balance_yet',$order['o_esp_money']);
                        // 店铺现金交易额
                        DB::name('shop')->where('shop_id',$order['o_shop_id'])->setInc ('shop_money_balance',$order['o_esp_money']);
                        // 店铺当日现金交易额// 定时任务，每日0点清空
                        DB::name('shop')->where('shop_id',$order['o_shop_id'])->setInc ('shop_today_balance',$order['o_esp_money']);
                        // 店铺现金交易1‰分红
                        $shop_user_id = DB::name('shop')
                                            ->where('shop_id',$order['o_shop_id'])
                                            ->value('shop_user_id');
                        $this->shop_profit($order['o_shop_id'],$shop_user_id,$order['o_esp_money'],3);
                    }
                    $this->checkYetMoney($order['o_shop_id']);
//---------------------------------产品池分佣结算 start ---------------------------------------------
                    if ($order['o_m_type'] == 2 || $order['o_m_type'] == 3) {
                        $pool = Db::name('m_record')
                            ->where('record_order_number', $order['o_order_num'])
                            ->where('record_from_type', 'in', '4,3,7,8')
                            ->select();
                        if ($pool) {
                            if ($order['o_m_user_id'] && $order['o_m_user_id'] > 0) {
                                $qu = Db::name('u_user')->where('user_id', $order['o_m_user_id'])->value('user_area');
                            }
                            foreach ($pool as $k => $v) {
                                if ($v['record_money'] > 0) {
                                    Db::name('u_user')->where('user_id', $v['record_user_id'])->setInc('user_m_pool_money', $v['record_money']);
                                }
                                if ($v['record_jifen'] > 0) {
                                    $this->jifenFlow($v['record_jifen'], $qu, $v['record_user_id'], 'poolFenYong');
                                    $quname = Db::name('area')->where('district_id', $qu)->value('district');
                                    $cc = [
                                        '3' => '用户购买' . $give['p_name'] . '商品返佣',
                                        '4' => '用户购买' . $give['p_name'] . '商品返佣',
                                        '7' => $give['p_name'] . '商品团团赚团长奖励',
                                        '8' => $give['p_name'] . '商品参与团团赚奖励',
                                    ];
                                    Db::name('jifen_consume')->insert(['consume_content' => $cc[$v['record_from_type']] . $v['record_jifen'] . "积分({$quname})", 'consume_user_id' => $v['record_user_id'], 'consume_add_time' => date('Y-m-d H:i:s')]);
                                }
                                //推送待定
//                        Db::name('jifen_consume')->insert(['consume_content'=>'购买产品池'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分','consume_user_id'=>$order['o_user_id'],'consume_add_time'=>date('Y-m-d H:i:s')]);
//                        Db::name('notice')->insert (['n_to'=>1,'n_title'=>'购买商品','n_content'=>'购买'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分','n_images'=>'','n_type'=>2,'n_user_id'=>$order['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
//                        $this->jpushUser(1,$order['o_user_id'],'购买'.$give['p_name'].'商品赠送'.$give['p_give'] * $ss['oi_num'].'积分',json([]));
                            }
                        }
                        Db::name('m_record')->where('record_order_number', $order['o_order_num'])->update([
                            'record_status'    => 2,
                            'record_sure_time' => date('Y-m-d H:i:s')
                        ]);
                    }
                    //---------------------------------产品池分佣结算 end ---------------------------------------------
                    Db::name('notice')->insert (['n_to'=>1,'n_title'=>'购物订单','n_content'=>'订单收货成功，等待买家评价','n_images'=>'','n_type'=>2,'n_user_id'=>$order['o_user_id'],'n_read'=>1,'n_delete'=>1,'n_time'=>date('Y-m-d H:i:s')]);
                    try {
                        $this->jpushUser(1,$order['o_user_id'],'订单收货成功，等待买家评价',json([]));
                    } catch (\Exception $e) {}
                    Db::commit ();
                }
            }
        }catch (\Exception $e){
            Db::rollback ();
            Log::record($e->getMessage(),'error');
        }
    }

    //计算未确认余额
    public function checkYetMoney($shop_id){
        $rat = Db::name('jifen_conf')->where('conf_id',2)->value('conf_rate');
        $money = Db::name('order')
            ->where(['o_shop_id'=>$shop_id,'o_status'=>['in','2,3'],'o_type'=>['in','1,2'],'o_esp'=>1])
            ->value("(SUM(o_money)+(SUM(o_jifen) * {$rat})+SUM(o_esp_money)) o_money");
        $moneyLess = Db::name('order')
            ->where(['o_shop_id'=>$shop_id,'o_status'=>['in','2,3'],'o_m_type'=>['in','2,3'],'o_type'=>2,'o_esp'=>1])
            ->sum("o_m_money");
        Db::name('shop')->where('shop_id',$shop_id)->setField ('shop_balance_yet',$money - $moneyLess);
    }

    public function ppp(){
//        $res = $this->jpushUser(1,12,"积分夺宝的已开奖，抱歉未中奖！",json([]));
        $res = $this->jpushShop(1,1,"收款1积分",json([]));
        dump($res);
    }

    /**
     * @cc获取access_token
     * @return mixed|object|string|\think\App
     */
    public function getAccessToken(){
        if(cache('access_token')){
            return cache('access_token');
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.config('mini.appId').'&secret='.config('mini.appSecret');
        $obj = https_request($url);
        $arr = json_decode($obj, true);
        if(isset($arr['errcode'])){
            return '';
        }
        cache('access_token', $arr['access_token'], $arr['expires_in']);
        return $arr['access_token'];
    }

    public function msgSecCheck($content){
        $access_token = $this->getAccessToken();
        if(empty($access_token)){
            return ['code'=>0,'msg'=>'参数错误！'];
        }
        $url = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' . $access_token;
//        $obj = $this->curl_post($url, ['content'=>$content, 'version'=>2,'openid'=>'ojOZc5MWIsCleuc40oH8y3Zh0LMA','scene'=>1]);
        $obj = $this->curl_post($url, ['content'=>$content]);
        $result = json_decode($obj, true);
        if(isset($result['errcode']) && $result['errcode'] != 0){
            return ['code'=>0,'msg'=>'存在违法违规内容！'];
        }
        return ['code'=>1, 'msg'=>'success'];
    }

    public function curl_post($url,$data = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    public function getRedYajinValue($oid,$red_rat)
    {
        //-----------算抵扣金额 start --------
        $red_yajin = 0;
        $red_oinfo = Db::name('order_info')
            ->where('oi_order_id',$oid)
            ->field('oi_num,oi_goods_id')
            ->select();
        foreach ($red_oinfo as $red_k => $red_v){
            $red_yj1 = Db::name('product')->where('p_id',$red_v['oi_goods_id'])->value('p_give');
            if($red_yj1){
                $red_yj2 = $red_yj1 * $red_v['oi_num'];
                $red_yajin += $red_yj2;
            }
        }
        $red_yajin_jian = $red_yajin * $red_rat;
        return $red_yajin_jian;
        //-----------算抵扣金额  end --------
    }
    //---------------------------------语音播报start-----------------------------------------------------
    public function returnNumstr($money)
    {
        $arr = [
            '000','001','002','003','004','005','006','007','008','009'
            ,'010','011','012','013','014','015'
        ];
        $moneyArr = explode('.',$money);
        $str = $arr[$moneyArr[0][0]] . '-';
        if(strlen($moneyArr[0]) == 2) {
            if($moneyArr[0][0] == 1) {
                $str = $arr[10] . '-';
            }else{
                $str .= $arr[10] . '-';
            }
            if($moneyArr[0][1] > 0) $str .= $arr[$moneyArr[0][1]] . '-';
        };
        if(strlen($moneyArr[0]) == 3) {
            $str .= $arr[11] . '-';
            if($moneyArr[0][1] > 0 || $moneyArr[0][2] > 0){
                $str .= $arr[$moneyArr[0][1]] . '-';
                if($moneyArr[0][1] > 0) $str .= $arr[10] . '-';
                if($moneyArr[0][2] > 0) $str .= $arr[$moneyArr[0][2]] . '-';
            }

        }
        if(strlen($moneyArr[0]) == 4) {
            $str .= $arr[12] . '-';
            if($moneyArr[0][1] > 0 || $moneyArr[0][2] > 0 || $moneyArr[0][3] > 0){
                $str .= $arr[$moneyArr[0][1]] . '-';
                if($moneyArr[0][1] > 0) {
                    $str .= $arr[11] . '-'; //百
                    if($moneyArr[0][2] > 0 || $moneyArr[0][3] > 0){
                        $str .= $arr[$moneyArr[0][2]] . '-';
                        if($moneyArr[0][2] > 0) $str .= $arr[10] . '-';
                        if($moneyArr[0][3] > 0) $str .= $arr[$moneyArr[0][3]] . '-';
                    }
                }else{
                    if($moneyArr[0][2] > 0 || $moneyArr[0][3] > 0){
                        if($moneyArr[0][2] > 0) {
                            $str .= $arr[$moneyArr[0][2]] . '-';
                            $str .= $arr[10] . '-';
                        }
                        if($moneyArr[0][3] > 0) $str .= $arr[$moneyArr[0][3]] . '-';
                    }
                }
            }
        };
        if(strlen($moneyArr[0]) == 5) {
            $str .= $arr[13] . '-';
            if($moneyArr[0][1] > 0 || $moneyArr[0][2] > 0 || $moneyArr[0][3] > 0 || $moneyArr[0][4] > 0){
                $str .= $arr[$moneyArr[0][1]] . '-';
                if($moneyArr[0][1] > 0) {
                    $str .= $arr[12] . '-'; //千
                    if($moneyArr[0][2] > 0){ //如果百大于0，要读出来
                        $str .= $arr[$moneyArr[0][2]] . '-';
                        $str .= $arr[11] . '-'; //百
                        if($moneyArr[0][3] > 0){
                            $str .= $arr[$moneyArr[0][3]] . '-'; //十的值一定要读
                            $str .= $arr[10] . '-';
                            if($moneyArr[0][4] > 0) $str .= $arr[$moneyArr[0][4]] . '-';
                        }else{
                            if($moneyArr[0][4] > 0){
                                $str .= $arr[$moneyArr[0][3]] . '-'; //十的值一定要读
                                $str .= $arr[$moneyArr[0][4]] . '-';
                            }
                        }
                    }else{
                        if($moneyArr[0][3] > 0 || $moneyArr[0][4] > 0) $str .= $arr[$moneyArr[0][2]] . '-'; //百的值读出来，单位不需要了
                        if($moneyArr[0][3] > 0){
                            $str .= $arr[$moneyArr[0][3]] . '-'; //十的值一定要读
                            $str .= $arr[10] . '-';
                            if($moneyArr[0][4] > 0) $str .= $arr[$moneyArr[0][4]] . '-';
                        }else{
                            if($moneyArr[0][4] > 0){
                                $str .= $arr[$moneyArr[0][4]] . '-';
                            }
                        }
                    }

                }else{
                    if($moneyArr[0][2] > 0){ //百位数有值要读出来
                        $str .= $arr[$moneyArr[0][2]] . '-';
                        $str .= $arr[11] . '-'; //百
                        if($moneyArr[0][3] > 0){
                            $str .= $arr[$moneyArr[0][3]] . '-'; //十的值一定要读
                            $str .= $arr[10] . '-';
                            if($moneyArr[0][4] > 0) $str .= $arr[$moneyArr[0][4]] . '-';
                        }else{
                            if($moneyArr[0][4] > 0){
                                $str .= $arr[$moneyArr[0][3]] . '-'; //十的值一定要读
                                $str .= $arr[$moneyArr[0][4]] . '-';
                            }
                        }
                    }else{
                        if($moneyArr[0][3] > 0){
                            $str .= $arr[$moneyArr[0][3]] . '-'; //十的值一定要读
                            $str .= $arr[10] . '-';
                            if($moneyArr[0][4] > 0) $str .= $arr[$moneyArr[0][4]] . '-';
                        }else{
                            if($moneyArr[0][4] > 0){
                                $str .= $arr[$moneyArr[0][4]] . '-';
                            }
                        }
                    }
                }
            }
        };
        if(isset($moneyArr[1])) {
            if($moneyArr[1] != '00'){
                $str .= $arr[14] . '-';
                if(strlen($moneyArr[1]) >= 1) $str .= $arr[$moneyArr[1][0]] . '-';
                if(strlen($moneyArr[1]) >= 2) $str .= $arr[$moneyArr[1][1]] . '-';
            }
        };
        $str = trim($str,'-');
        return $str;
    }
    public function sayMyName($shop_id,$money,$jifen,$num,$type=1)
    {
        try {
            $num .= rand(10000, 99999);
            $have = Db::table('up_shop_ercode')
                ->where('ss_shop_id', $shop_id)
                ->find();
            if ($have) {
                if ($type == 3) {
                    $playAudibleMsg = '107';
                } else {
                    $moneyStr = $this->returnNumstr($money);
                    $playAudibleMsg = '200-' . $moneyStr . '-015';
                    if ($type == 1) {
                        if ($jifen && $jifen > 0) {
                            $jifenStr = $this->returnNumstr($jifen);
                            $playAudibleMsg .= '-201-' . $jifenStr . '-202';
                        } else {
                            $playAudibleMsg .= '-203';
                        }
                    } else {
                        $playAudibleMsg = '204-' . $moneyStr . '-015';
                    }
                }

                $sample = new \app\api\controller\Sample();
                $arr = [
                    "iotInstanceId" => "iot-06z00c4umzx0t2q",
                    "qos" => 0,
                    "topicFullName" => "/ggbgIwhmZvC/{$have['ss_about_name']}/user/get",
                    "productKey" => "ggbgIwhmZvC",
                    "messageContent" => base64_encode('{"playAudibleMsg":"' . $playAudibleMsg . '","orderId":"' . $num . '"}')
                ];
                $sample->main($arr);
            }
            return '';
        }catch (\Exception $e) {
            return '';
        }
    }
    //---------------------------------语音播报end-----------------------------------------------------
    //只是为了测试语音播报设备（此方法没啥用）
//    public function hhh(){
//        $this->sayMyName2(977,1,1,time());
//    }
//    public function sayMyName2($shop_id,$money,$jifen,$num,$type=1)
//    {
//        $num .= rand(10000, 99999);
//        $have = Db::table('up_shop_ercode')
//            ->where('ss_shop_id', $shop_id)
//            ->find();
//        if ($have) {
//            if ($type == 3) {
//                $playAudibleMsg = '107';
//            } else {
//                $moneyStr = $this->returnNumstr($money);
//                $playAudibleMsg = '200-' . $moneyStr . '-015';
//                if ($type == 1) {
//                    if ($jifen && $jifen > 0) {
//                        $jifenStr = $this->returnNumstr($jifen);
//                        $playAudibleMsg .= '-201-' . $jifenStr . '-202';
//                    } else {
//                        $playAudibleMsg .= '-203';
//                    }
//                } else {
//                    $playAudibleMsg = '204-' . $moneyStr . '-015';
//                }
//            }
//
//            $sample = new \app\api\controller\Sample();
//            $arr = [
//                "iotInstanceId" => "iot-06z00c4umzx0t2q",
//                "qos" => 0,
//                "topicFullName" => "/ggbgIwhmZvC/{$have['ss_about_name']}/user/get",
//                "productKey" => "ggbgIwhmZvC",
//                "messageContent" => base64_encode('{"playAudibleMsg":"' . $playAudibleMsg . '","orderId":"' . $num . '"}')
//            ];
//            $sample->main($arr);
//        }
//    }
}